首页 > 解决方案 > 数组排序与否?基础级 Java

问题描述

我正在尝试制作一个程序来告诉我我的数组是否已排序(升序和降序)。

我创建了一个函数,如果返回 true,则数组已经排序,如果返回 false,则数组未排序。

实际上,总是得到“未排序”。我不知道逻辑是否正确,但我认为是的,我不知道。

你们能帮帮我吗,伙计们?

package exercici11;

import java.util.Scanner;

public class SortedOrNot {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int[] myArray = new int[10];
        int prev1 = 0;
        int prev2 = 0;
        int cont1 = 0;
        int cont2 = 0;

        System.out.print("Enter 10 numbers: ");

        for (int i = 0; i < myArray.length; i++) {
            myArray[i] = sc.nextInt();
        }

        String result = isSorted(myArray, prev1, prev2, cont1, cont2) ? result = "Is sorted." : "Is not sorted.";
        System.out.println(result);

        sc.close();

    }

    private static boolean isSorted(int[] myArray, int prev1, int prev2, int cont1, int cont2) {
        for (int i = 0; i < myArray.length; i++) {
            for (int j = 0; j < myArray.length; j++) {
                prev1 = myArray[i];
                if (prev1 < myArray[i]) {
                    // Ascending sort
                    cont1++;
                    if (cont1 == 10) {
                        return true;
                    }
                } else if (prev2 > myArray[i]) {
                    // Descending sort
                    cont2++;
                    if (cont2 == 10) {
                        // Ascending sort
                        return true;
                    }
                }
            }
        }
        return false;
    }

}

谢谢!

问候,亚历克斯。

标签: java

解决方案


我改变了isSorted()方法并添加了一些评论。

import java.util.Scanner;

public class SortedOrNot {

public static void main(String[] args) {

    Scanner sc = new Scanner(System.in);
    int[] myArray = new int[10];

    System.out.print("Enter 10 numbers: ");

    for (int i = 0; i < myArray.length; i++) {
        myArray[i] = sc.nextInt();
    }

    String result = isSorted(myArray) ? result = "Is sorted." : "Is not sorted.";
    System.out.println(result);

    sc.close();

}

private static boolean isSorted(int[] myArray) {
    int count = 0;
    int firstElement = myArray[0];
    int lastElement = myArray[myArray.length - 1];
    if(lastElement - firstElement >= 0){ 
    // Let's say myArray is sorted and if (lastElement - firstElement) >= 0
    // then I check if the elements from array are in ascending order
    // OR are all the same
        for(int i = 0; i < myArray.length - 1; i++){
            if(myArray[i] <= myArray[i + 1]) {
                count++;
            }
        }
    }
    else {
    // else I check if the elements from array are in descending order
        for(int i = 0; i < myArray.length - 1; i++){
            if(myArray[i] >= myArray[i + 1]){
                count++;
            }
        }
    }

    // for n numbers there will be n - 1 comparisons
    return count == myArray.length - 1;
}

}

推荐阅读