zoukankan      html  css  js  c++  java
  • 自定义定制排序

    sort() 方法自然排序 【默认:从小到大】

    package com.arrays;
    
    import java.util.Arrays;
    import java.util.Comparator;
    
    public class ArrarysCommonMethods {
        public static void main(String[] args) {
            // sort 排序 (自然排序和定制排序) Integer arr[] ={1, 3, 2, 4, 0, 9, -5};
            int arr[] = { 1, 3, 2, 4, 0, 9, -5 };
            Arrays.sort(arr);
    
            // 输出数组
            System.out.println(Arrays.toString(arr)); // 总是【默认】从小到大输出
      }
    }

    使用系统的 Comparator 接口实现定制排序

    import java.util.Arrays;
    import java.util.Comparator;
    
    public class ArrarysCommonMethods {
        public static void main(String[] args) {
            
         // 【定制排序】
        Integer arrs[] = { 1, 3, 2, 4, 0, 9, -5 }; // 装箱
        Arrays.sort(arrs, new Comparator<Integer>() {
    
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1; // 将o2和o1位置互换又为从小到大
            }
        });
    
        System.out.println("arrs定制排序后" + Arrays.toString(arrs));    
      }
    }

    使用冒泡法实现自定义定制排序

    import java.util.Arrays;
    import java.util.Comparator;
    
    public class ArrarysCommonMethods {
        public static void main(String[] args) {
            
         // 默认实现如何实现定制排序的
         // 使用冒泡法完成
        int myarr[] = { 1, -1, 4, 3, 9, -2, 8 };
        MyArrys.sort(myarr, new MyComparator() {
                
            @Override
            public int compare(int n1, int n2) {
                return n2-n1;
            }
        });
        System.out.println("自己使用冒泡写的定制排序:" + Arrays.toString(myarr));
        }
    }
    
    interface MyComparator {
        public int compare(int n1, int n2);
    }
    
    class MyArrys {
        // 静态方法
        public static void sort(int[] arr, MyComparator comparator) {
            // 冒泡
            int temp = 0;
            for (int i = 0; i < arr.length - 1; i++) {
                for (int j = 0; j < arr.length - 1 - i; j++) {
                    // 判断
                    if (comparator.compare(arr[j], arr[j + 1]) > 0) {
                        // 交换
                        temp = arr[j];
                        arr[j] = arr[j + 1];
                        arr[j + 1] = temp;
                    }
                }
            }
        }
    }    
  • 相关阅读:
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Live2D 看板娘
    Bound mismatch: The typae CertificateDirectory is not a valid substitute for the bounded parameter <M extends Serializable>
    Duplicate property mapping of contactPhone found in
  • 原文地址:https://www.cnblogs.com/yonxin/p/12470435.html
Copyright © 2011-2022 走看看