java黑皮书课后习题7.19

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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值