计数排序

import java.util.Arrays;

public class My {
    public void countSort(int[] arr) {
        int max = arr[0];
        int min = arr[0];
        for (int a : arr) {
            if (a > max) {
                max = a;
            }
            if (a < min) {
                min = a;
            }
        }
        int[] count = new int[max - min + 1];
        for (int a : arr) {
            count[a - min]++;
        }
        for (int i = 1; i < count.length; i++) {
            count[i] += count[i - 1];
        }
        int[] result = new int[arr.length];
        for (int i = arr.length - 1; i >= 0; i--) {
            result[count[arr[i] - min] - 1] = arr[i];
            count[arr[i] - min]--;
        }
        System.arraycopy(result, 0, arr, 0, arr.length);
    }

    public static void main(String[] args) {
        My my = new My();
        int[] arr = {5, 6, 1, 2, 4, 7, 2, 3, 4, 6, 4};
        my.countSort(arr);
        System.out.println(Arrays.toString(arr));
    }
}

 

你可能感兴趣的:(计数排序)