One, counting sort
Count sort (counting sort) is a stable sort algorithm
The steps of the algorithm are as follows:
Find the largest and smallest elements in an array to be sorted
Counts the number of occurrences of an element in an array of I, in the first item of the array C
Add to all counts (starting with the first element in C, and adding each item to the previous item)
To reverse populate the target array: Place each element I in the new array in subparagraph C (i), minus 1 for each element
When the input element is an integer between n 0 to K, the time complexity of the count order is O (n+k), and the space complexity is O (n+k). When k is not very large, this is a very effective linear sorting algorithm.
Here is the test code:
Copy Code code as follows:
#-*-Coding:utf8-*-
Import Random
def jishu (data, max):
"""
Cardinality ordering: When the input element is an integer between n 0 to K (K cannot be too large, that is, Max cannot be too large)
@param data: Arrays that need to be sorted
@param Max: The largest number
"""
results = [None for i in Xrange (len (data)]] # The final result
c = [0 for I in range (max+1)]
# Use array c to count the number of elements per value =d
For D in data:
C[D] = C[d] + 1
# C[i] Represents the number of elements in the value <=i in the data
For I in range (1, max+1):
C[i] = C[i] + c[i-1]
# The elements in C are printed backwards and are sorted.
For j in Xrange (Len (data)-1,-1,-1):
RESULT[C[DATA[J]]-1] = Data[j]
C[DATA[J]] = c[data[j]]–1
return result
if __name__ = = ' __main__ ':
#制造1000个0到100的数字
Print Jishu ([random.randint (0) for I in range (1000)], 100)
Second, the Cardinal order
The cardinality sort sort is a radix integer sort algorithm that cuts integers by bits to different numbers, and then compares them by each number of digits.
This is done by unifying all the values to be compared (positive integers) to the same number of digits, preceded by a short number of 0. Then, start at the lowest bit, and then sort it one at a time. This is done from the lowest bit to the highest order, and the sequence becomes an ordered series.
Cardinality sorting can take the form of LSD (least significant digital) or MSD (Most significant), and the sort of LSD starts at the far right of the key value, and digital, on the other hand, starting at the far left of the key value.
Here is a test case:
Copy Code code as follows:
#-*-Coding:utf8-*-
Import Random
def jichu (data, length):
"""
Cardinal Row LSD
@param data: Combinations that need to be sorted
@param length: The largest data is a few
"""
For L in xrange (length):
s = [[] for I in Xrange (10)]
For D in data:
s[d/(10**l)% 10].append (d)
data = [D for s_list in S for D in S_list]
Return data
if __name__ = = ' __main__ ':
List = [Random.randint (1, 99999999) for I in Xrange (99)] # Manufacturing 99 data
Print Jichu (list, 8)