Python algorithm learning-counting sorting instance
Copy codeThe Code is as follows:
#-*-Coding: UTF-8 -*-
Def _ counting_sort (A, B, k ):
"Counts are sorted. The pseudo code is as follows:
COUNTING-SORT (A, B, k)
1 for I defaults 0 to k // initialize the value of the bucket
2 do C [I] defaults 0
3 for j every 1 to length [A] // count each value
4 do C [A [j] ← C [A [j] + 1
5. Objective C [I] contains the number of elements equal to I
6 for I limit 1 to k // calculate the sum of counts and determine the number of elements <= each value
7 do C [I] ← C [I] + C [I-1]
8. Objective C [I] contains the number of elements smaller than or equal to I
9 for j segment length [A] downto 1
10 do B [C [A [j] Then A [j] // place the [j] value in the corresponding position
11 C [A [j] ← C [A [j]-1 // avoid element overwriting at the same time
T (n) = θ (n)
Args:
A (Sequence): original array
B (Sequence): Result Array
K (int): the maximum value. It is assumed that all elements are between [0, k].
"""
Len_c = k + 1
C = [0] * len_c
For a in:
C [a] = C [a] + 1
For I in range (1, len_c ):
C [I] = C [I] + C [I-1]
For a in A [:-1]:
B [C [a]-1] =
C [a] = C [a]-1
Def counting_sort ():
"Assuming that all elements in array A are between [0, len (A)-1]"
B = [0] * len ()
_ Counting_sort (A, B, len (A)-1)
Return B
If _ name _ = '_ main __':
Import random, timeit
Items = range (1, 10000)
Random. shuffle (items)
Def test_sorted ():
Print (items)
Sorted_items = sorted (items)
Print (sorted_items)
Def test_counting_sort ():
Print (items)
Sorted_items = counting_sort (items)
Print (sorted_items)
Test_methods = [test_sorted, test_counting_sort]
For test in test_methods:
Name = test. _ name _ # test. func_name
T = timeit. Timer (name + '()', 'From _ main _ import '+ name)
Print (name + 'takes time: % F' % t. timeit (1 ))