您的位置 首页 java

Java数组排序

Arrays.sort()

    int[] num = { 111, 112, 3, 35, 3, 33 };
        Arrays.sort(num);
        for (int no : num) {
            System.out.println(no);
        }  

冒泡排序算法

相邻的两个元素进行比较,如果符合条件换位

   public static void main(String[] args) {
        // write your code here
        int[] num = {111, 112, 3, 35, 3, 33};
        int[] numSort = sort(num);
        for (int no : numSort) {
            System.out.println(no);
        }

    }

    public static int[] sort(int[] args) {//冒泡排序算法
        for (int i = 0; i < args.length - 1; i++) {
            for (int j = i + 1; j < args.length; j++) {
                if (args[i] > args[j]) {
                    int temp = args[i];
                    args[i] = args[j];
                    args[j] = temp;
                }
            }
        }
        return args;
    }  

选择排序算法

 public static void main(String[] args) {
        // write your code here
        int[] num = {111, 112, 3, 35, 3, 33};
        int[] numSort = sort(num);
        for (int no : numSort) {
            System.out.println(no);
        }

    }

    public static int[] sort(int[] args) {// 选择排序算法
        for (int i = 0; i < args.length - 1; i++) {
            int min = i;
            for (int j = i + 1; j < args.length; j++) {
                if (args[min] > args[j]) {
                    min = j;
                }
            }
            if (min != i) {
                int temp = args[i];
                args[i] = args[min];
                args[min] = temp;
            }
        }
        return args;
    }  

插入排序算法

 public static void main(String[] args) {
        // write your code here
        int[] num = {111, 112, 3, 35, 3, 33};
        int[] numSort = sort(num);
        for (int no : numSort) {
            System.out.println(no);
        }

    }

    public static int[] sort(int[] args) {//插入排序算法
        for (int i = 1; i < args.length; i++) {
            for (int j = i; j > 0; j--) {
                if (args[j] < args[j - 1]) {
                    int temp = args[j - 1];
                    args[j - 1] = args[j];
                    args[j] = temp;
                } else break;
            }
        }
        return args;
    }  

以上就是java中的四种排序方法

文章来源:智云一二三科技

文章标题:Java数组排序

文章地址:https://www.zhihuclub.com/174286.shtml

关于作者: 智云科技

热门文章

网站地图