算法 线性排序-区间法

public class Sort {
    public static int[] sort(int[] a) {
        int min = Integer.MAX_VALUE;
        int max = Integer.MIN_VALUE;

        Map counts = new HashMap();

        for (int i = 0; i < a.length; i++) {
            if (a[i] < min) {
                min = a[i];
            }
            if (a[i] > max) {
                max = a[i];
            }
            if (counts.containsKey(a[i])) {
                counts.put(a[i], counts.get(a[i]) + 1);
            } else {
                counts.put(a[i], 1);
            }
        }

        int c = 0;
        for (int i = min; i <= max; i++) {
            if (counts.containsKey(i)) {
                for (int j = 0; j < counts.get(i); j++) {
                    a[c++] = i;
                }
            }
        }
        return a;
    }

    public static void main(String[] args) {
        int[] a = {4, 3, 2, 5, 3, 6, 2, 10, 8, 12, 6, 7};
        sort(a);
        System.out.println(Arrays.toString(a));
    }
}

你可能感兴趣的:(算法,java,排序算法,java)