Sorting algorithm of counting sort (Java version)

Count sorting is a sorting algorithm that is not based on comparison. Its advantage is that when sorting integers within a certain range, its complexity is Ο(n+k) (where k is the range of integers), which is faster than any comparison sorting algorithm. Of course, this is an algorithm that sacrifices space for time.

Basic idea

The basic idea of ​​counting and sorting is: for each input element x, determine the number of elements less than x. For example, if there are 7 elements less than x, then x should be in the 8th output position.

working process

  • Preparation:
    Input array: array[1...n].
    Output array: result[1...n].
    Temporarily store the array: countArray[0...k].
  • arrayThe number of each element in the calculation is stored in the countArrayarray: the arrayvalue of the element in the countArrayarray is used as the subscript of the array, and the element in the array is arrayrepeated once every time the countArraycorresponding element of the array is +1.
  • Calculate arraythe number less than the current element in the countArrayarray = the sum of the current element and the previous element in the array. And update the data to the countArrayarray
  • According countArrayto determine the current element in the array is less than the number arrayof elements in the array of resultstorage positions in the array.

Code

    /**
     * 计数排序
     * @param array 待排序数组
     * @param k 临时数组长度,取值为排序数组的最大值+1
     *          (此处是因为 array 中的元素被作为数组下标,所以数组长度为最大值+1)
     */
    private static void countSort(int[] array, int k) {
    
    
        //创建计数统计数组
        int[] countArray = new int[k];
        //计算 array 中每个元素的重复个数
        for (int i = 0; i < array.length; i++) {
    
    
            countArray[array[i]] += 1;
        }
        //计算数组中小于当前元素的元素个数
        for (int i = 0; i < k; i++) {
    
    
            if (i > 0) {
    
    
                countArray[i] = countArray[i] + countArray[i - 1];
            }
        }
        //结果输出数组
        int[] result = new int[array.length];
        //将 array 中的元素存放到 result 指定位置
        for (int i = array.length - 1; i >= 0; i--) {
    
    
            System.out.println("array:" + array[i] + " | countArray:" + countArray[array[i]]);
            //计算存放位置(小于当前元素的数量值-1即为数组下标)
            int pos = countArray[array[i]] -1;
            //根据计数统计数组将数组array中的元素存放到result数组中
            result[pos] = array[i];
            //小于当前元素的数量值-1
            countArray[array[i]] = pos;
        }
        
        System.out.println(Arrays.toString(result));

    }

Late update, haha. Counting sorting feels like an algorithm that is not commonly used, but the idea is more peculiar than other comparison sorting, and it is worth understanding and learning.

Guess you like

Origin blog.csdn.net/lijie2664989/article/details/85042679