您好,欢迎来到画鸵萌宠网。
搜索
您的当前位置:首页java黑皮书课后习题7.19

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;
    }
}

因篇幅问题不能全部显示,请点此查看更多更全内容

Copyright © 2019- huatuo8.com 版权所有 湘ICP备2023022238号-1

违法及侵权请联系:TEL:199 1889 7713 E-MAIL:2724546146@qq.com

本站由北京市万商天勤律师事务所王兴未律师提供法律服务