Sort - Count - optimized version

Counting Sort optimized version: 
quote: https: //www.cnblogs.com/xiaochuan94/p/11198610.html
basic version can solve the general case, but it has a flaw, it is that there is space wasted.
For example, one set of data {} 101,109,108,102,110,107,103, wherein the maximum value 110, in accordance with the basic version of the idea, as
we need to create a count length of the array 111, but we can find, [0,100] is completely wasted space in front of it, and
then how optimize?
The length of the array as max-min + 1, i.e., only to find the maximum value, but also to identify the minimum value, to determine the length of the array in accordance with the count difference between the two.

python algorithm:
Import Math 

DEF countSort (data):
     # assumption greatly minimum negative infinity, the maximum positive infinity greatly 
    listMin = a float ( " INF " ) 
    listMax = a float ( " -INF " )
     # find the maximum value of the array data, the minimum 
    for I in Data: 
        listMax = max (I, listMax) 
        listMin = min (I, listMin)
     # initialization count array cOUNT 
    countList = [0] * (listMax - listMin +. 1 )
     # on each of the element count array assignment, data list value, i.e., the index is countList, 
    # index position corresponding to the value of the number indicates the number that appears, to the elements countList subtracting the minimum value, then a new index
    for I in Data: 
        countList [I -listMin] +. 1 =
     # Create a result array 
    resultList = [0] * len (Data)
     # Create the resulting array starting index 
    index = 0
     for I in Range (len (countList)):
         # only the number of times is greater than 0 statistics appear, when its value is greater than 0, the number of instructions that appear 
        the while countList [i]> 0:
             # value of i denote the number of comparisons required list, then subtracting the minimum complement on 
            resultList [index] = I + listMin 
            index +. 1 =
             # of occurrences Save. 1 
            countList [I] - =. 1 return resultList DEF
    


main (): 
    Data = List (Map (int, INPUT ( " Enter a list to be sorted, separated by commas: " ) .split ( " , " )))
     # 101,109,108,102,110,107,103 
    RTN = countSort (Data)
     Print ( " counting sequencing results is: " , End = " " )
     Print (RTN) 

IF  the __name__ == " __main__ " : 
    main ()

 

 

Guess you like

Origin www.cnblogs.com/an-wl/p/12631457.html