MCPcopy Create free account
hub / github.com/geekcomputers/Python / counting_sort

Function counting_sort

Sorting Algorithms/Counting-sort.py:9–39  ·  view source on GitHub ↗

Counting sort algo with sort in place. Args: tlist: target list to sort k: max value assume known before hand n: the length of the given list map info to index of the count list. Adv: The count (after cum sum) will hold the actual position of the eleme

(tlist, k, n)

Source from the content-addressed store, hash-verified

7
8
9def counting_sort(tlist, k, n):
10 """Counting sort algo with sort in place.
11 Args:
12 tlist: target list to sort
13 k: max value assume known before hand
14 n: the length of the given list
15 map info to index of the count list.
16 Adv:
17 The count (after cum sum) will hold the actual position of the element in sorted order
18 Using the above,
19
20 """
21
22 # Create a count list and using the index to map to the integer in tlist.
23 count_list = [0] * (k + 1)
24
25 # iterate the tgt_list to put into count list
26 for i in range(0, n):
27 count_list[tlist[i]] += 1
28
29 # Modify count list such that each index of count list is the combined sum of the previous counts
30 # each index indicate the actual position (or sequence) in the output sequence.
31 for i in range(1, k + 1):
32 count_list[i] = count_list[i] + count_list[i - 1]
33
34 flist = [0] * (n)
35 for i in range(n - 1, -1, -1):
36 count_list[tlist[i]] = count_list[tlist[i]] - 1
37 flist[count_list[tlist[i]]] = tlist[i]
38
39 return flist
40
41
42flist = counting_sort(tlist, k, n)

Callers 1

Counting-sort.pyFile · 0.70

Calls

no outgoing calls

Tested by

no test coverage detected