第七章第十九题(是否排序好了)(Is it sorted)
-
**7.19(是否排序好了)编写以下方法,如果参数中的list数组已经按照升序排好了,则返回true。
public static boolean isSorted(int[] list)
编写一个测试程序,题数用户输入一个列表,显示该列表会否已经排好序。下面是一个运行示例。注意,输入中的第一个数表示列表中的元素个数。该数不是列表的一部分。
Enter the size of the list:8
Enter the contents of the list:10 1 5 16 61 9 11 1
The list has 8 integers 10 1 5 16 61 9 11 1
The list is not sorted
Enter the size of the list:10
Enter the contents of the list:1 1 3 4 4 5 7 9 11 21
The list has 10 integers 1 1 3 4 4 5 7 9 11 21
The list is already sorted
**7.19(Is it sorted)If the list array in the parameter has been sorted in ascending order, it will return true.
public static boolean isSorted(int[] list)
Write a test program, the number of questions the user input a list to show whether the list has been arranged in order. Here is a running example. Note that the first number in the input represents the number of elements in the list. The number is not part of the list.
Enter the size of the list:8
Enter the contents of the list:10 1 5 16 61 9 11 1
The list has 8 integers 10 1 5 16 61 9 11 1
The list is not sorted
Enter the size of the list:10
Enter the contents of the list:1 1 3 4 4 5 7 9 11 21
The list has 10 integers 1 1 3 4 4 5 7 9 11 21
The list is already sorted -
参考代码:
package chapter07; import java.util.Scanner; public class Code_19 { public static void main(String[] args) { System.out.print("Enter the size of the list:"); Scanner input = new Scanner(System.in); int number = input.nextInt(); int[] list = new int[number]; System.out.print("Enter the contents of the list:"); for(int i = 0;i < list.length;i++){ list[i] = input.nextInt(); } System.out.print("The list has " + number + " integers "); for(int i = 0;i < list.length;i++){ System.out.print(list[i] + " "); } if(!isSorted(list)){ System.out.println("\nThe list is not sorted"); } else System.out.println("\nThe list is already sorted"); } public static boolean isSorted(int[] list){ for(int i = 1;i < list.length;i++){ if(list[i-1] > list[i]){ return false; } } return true; } }
-
结果显示:
Enter the size of the list:10 Enter the contents of the list:1 1 3 4 4 5 7 9 11 21 The list has 10 integers 1 1 3 4 4 5 7 9 11 21 The list is already sorted Process finished with exit code 0