import java.util.Scanner;
import java.util.Arrays;
class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter the amount of numbers to be checked for sort");
int amount = input.nextInt();
int[] list = new int[amount];
for (int i = 0; i < list.length; i++) {
System.out.print("Enter a number: ");
list[i] = input.nextInt();
}
// Print the original array
printArray(list);
// list2 will contain the sorted list of elements
int[] list2 = sortArray(list);
printArray(list2);
// Print the results
if (Arrays.equals(list, list2)) {
System.out.println("Already sorted!");
} else {
System.out.println("Not sorted");
}
}
// Print array method
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
}
// function to sort the array
public static int[] sortArray(int[] array) {
boolean changed = true;
do {
changed = false;
for (int i = 0; i < array.length - 1; i++) {
if (array[i] > array[i + 1]) {
// swap array[i] with array[i + 1]
int temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
changed = true;
}
}
} while (changed);
return array;
}
}
原题: 编写一个测试程序,提示用户输入一个列表,并显示该列表是否排序。这是一个示例运行。请注意,输入中的第一个数字表示列表中元素的数量。
我的问题: 为什么我得到“已经排序!” 即使我输入未排序的列表?
运行程序时的输出:
gurbhej@Nanda:~/Dropbox/Programming/Java Programs/Test$ java Test
Enter the amount of numbers to be checked for sort
5
Enter a number: 4
Enter a number: 3
Enter a number: 5
Enter a number: 6
Enter a number: 3
Unsorted
4
3
5
6
3
Sorted
3
3
4
5
6
Already sorted!
gurbhej@Nanda:~/Dropbox/Programming/Java Programs/Test$