Skip to content

Commit 204fbf3

Browse files
added Python implementation of Counting Sort
1 parent 6c0ffb9 commit 204fbf3

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
def countSort(a):
2+
k = max(a)+1
3+
count = [0]*k
4+
5+
# calculate the histogtam of key frequencies
6+
for x in a:
7+
count[x] += 1
8+
9+
# calculate the starting index for each key
10+
total = 0
11+
for i in range(k):
12+
oldCount = count[i]
13+
count[i] = total
14+
total += oldCount
15+
16+
# copy to output array, preserving order of inputs with equal keys
17+
output = [0]*len(a)
18+
for x in a:
19+
output[count[x]] = x
20+
count[x] += 1
21+
22+
return output
23+
24+
25+
if __name__ == '__main__':
26+
a = [3,8,25,11,1,31,6,3,11]
27+
print "Unsorted list: ", a
28+
a = countSort(a)
29+
print "Sorted list: ", a

0 commit comments

Comments
 (0)