Sorting algorithms - Counting Sort (Java)

com.rao.sort Package; 

Import java.util.Arrays; 

/ * * 
 * @author Srao 
 * @className CountSort 
 * @date 2019/12/9 14:47 
 * @package com.rao.sort 
 * @Description counting sequencing 
 * / 
public  class countSort { 

    / * * 
     * counting sequencing 
     * @param arr: array to be sorted 
     * @return 
     * / 
    public  static  int [] countSort ( int [] ARR) {
         int n-= arr.length;
         // define two variables used to store the maximum and minimum array 
        int min = ARR [ 0 ];
         int max = ARR [0 ];
         for ( int I = . 1 ; I <n-; I ++ ) {
             IF (max < ARR [I]) { 
                max = ARR [I]; 
            } 
            IF (ARR [I] < min) { 
                min = ARR [I ]; 
            } 
        } 
        // define an array of length len, is done to prevent the minimum value in the array is 1000 and the maximum value 1010
         // this creates an array of size on the line 10, without creating size 1010 array, wasted space 
        int len = max - min + . 1 ;
         // which appeared in a digital, digital storage put it up as a subscript, if 1006 appears once, put temp [1006-1000] plus one 
        int [ ] temp =new new  int [len];
         for ( int I = 0 ; I <n-; I ++ ) { 
            temp [ARR [I] - min] ++ ; 
        } 
        int K = 0 ;
         // to traverse temp, temp [i] of value is the number of times i appears added temp [5] = 3, description (5 + 1000) appeared three times 
        for ( int i = 0 ; i <len; i ++ ) {
             for ( int J = TEMP [i]; J > 0 ; J, ) { 
                ARR [K] = I + min; 
                K ++ ;  
            }
        }

        return arr;
    }

    public static void main(String[] args) {
        int[] arr = {3, 6, 9, 5, 0};
        System.out.println(Arrays.toString(arr));
        arr = countSort(arr);
        System.out.println(Arrays.toString(arr));

    }
}

  Adapted to count sort is a difference between the maximum and minimum values ​​are not sorted not great.

  The basic idea: is the array element as a subscript of the array, the number of times the element occurs with a temporary array and statistics, e.g. temp [i] = m, i represents an element of a total of m times occurred. And finally the temporary array of statistical data from small to large Taken together, this time it is a summary of the data is ordered.

Guess you like

Origin www.cnblogs.com/rao11/p/12011095.html