我有一個程序,檢查列表是否排序。我如何打印答案? (即「列表已排序」,「列表未排序」)。Sorted/Not sorted - 如何將答案打印到控制檯?
public class CheckList {
public static void main(String[] args) {
int[] myList = new int[10];
// Read in ten numbers
Scanner input = new Scanner(System.in);
System.out.println("Enter ten numbers: ");
for (int i = 0; i < myList.length; i++) {
myList[i] = input.nextInt();
}
}
//Check if list is sorted
public static boolean isSorted(int[] myList) {
if (myList[0] > 1) {
for (int i = 1; i < myList[0]; i++)
if (myList[i] > myList[i + 1])
return false;
}
return true;
}
}
順便說一句,isSorted方法只是檢查數組是否升序排序。即使數組按降序排序,它也會返回false。 – user1401472
@ user1401472它不會,當到達'myList [0]'時停止,所以如果我有一個3個元素的數組,並且'myList [0] = 5',則該方法會在某些時候拋出一個'IndexOutOfBoundsException'點。該算法不起作用:) – BackSlash