public class Exercise07_19 { public static void main(String[] args) { java.util.Scanner sc = new java.util.Scanner(System.in); System.out.print("Enter the size of the list:"); int numbers = sc.nextInt(); int[] array = new int[numbers]; System.out.print("Enter the contents of the list:"); for (int i = 0; i < array.length; i++){ array[i] = sc.nextInt(); } if (isSorted(array)) System.out.println("The list is already sorted"); else System.out.println("The list is not sorted"); } public static boolean isSorted(int[] list){//是否升序排序 int[] array = new int[list.length]; //只能将list中的各个位置元素赋值给array相应位置,不能int[] array = list; // 因为这样array与list指向同一内存空间的起始地址,修改array即修改list,最终结果都是返回true for (int i = 0; i < array.length; i++) array[i] = list[i]; java.util.Arrays.sort(array); //下列注释为如何升序排序,当然可如上一行调用一个Arrays类方法sort解决 // for (int i = 0; i < array.length - 1; i++){//升序排序 // int currentMin = array[i];//假设当前i下标元素最小 // int currentMinIndex = i; // for (int j = i + 1; j < array.length; j++){ // if (currentMin > array[j]){ // currentMin = array[j]; // currentMinIndex = j; // } // } // if (currentMinIndex != i){//如果当前最小值不位于下标i,则互换元素 // array[currentMinIndex] = array[i]; // array[i] = currentMin; // } // } for (int i = 0; i < list.length; i++){ if (list[i] != array[i]) return false; } return true; } }