编写一个测试程序,提示用户输入一个列表,显示该列表是否已经排好序。
import java.util.Scanner;
public class HomeWork4 {
public static boolean isSorted(int[] list) {
int flag=1;
for(int i=1;i<list.length-1;i++) {
if(list[i-1]>list[i])
flag=0;
}
if(flag==0)
return false;
else
return true;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the size of the list: ");
int n = input.nextInt();
int[] array = new int[n];
System.out.print("Enter the contents of the list: ");
for(int i=0;i<n;i++) {
array[i]=input.nextInt();
}
System.out.print("The list has " + n + " integers ");
for(int i=0;i<n;i++) {
System.out.print(array[i]+" ");
}
System.out.println("");
if(isSorted(array))
System.out.println("The list is already sorted");
else
System.out.println("The list is not sorted");
input.close();
}
}
运行结果: