计数排序模板

  1. 遍历整个待排序数组找出最小值min、最大值max
  2. 建立一个统计数组cntArray(用于统计待排序数组中每个数出现的频率),长度为max - min + 1
  3. 遍历整个待排序数组统计每个数出现的频率
  4. 依次遍历从min ~ max的数,找到每个数的频率ct并将该数放ct次到待排序数组中
public class CounterSort {
    public static void main(String[] args) {
        CounterSort counterSort = new CounterSort();
        int[] arr = {5, 1, 1, 2, 0, 0};
        counterSort.counterSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static int[] sortArray(int[] nums) {
        counterSort(nums);
        return nums;
    }

    private static void counterSort(int[] nums) {
        int min = 0x7fffffff, max = 0x80000000;
        for (int num : nums) {
            min = Math.min(min, num);
            max = Math.max(max, num);
        }
        int[] cnt = new int[max - min + 1];
        for (int num : nums) {
            cnt[num - min]++;
        }
        int idx = 0;
        for (int num = min; num <= max; num++) {
            int ct = cnt[num - min];
            while (ct > 0) {
                nums[idx++] = num;
                ct--;
            }
        }
    }
}

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