Skip to content

Commit 51ccee9

Browse files
committed
Added counting sort for Python
1 parent ceb8049 commit 51ccee9

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
def counting_sort(A, max_val):
2+
"""
3+
This soring algorithm will only works with array length n consist of
4+
elements from 0 to k for integer k < n.
5+
"""
6+
k = max_val + 1
7+
count = [0]*k
8+
result = [None]*len(A)
9+
10+
print("Array A = ", A)
11+
12+
# counting the number of i (1 < i < k) in A and store in count
13+
for i in A:
14+
count[i] += 1
15+
16+
print("Counting array (storing number of elements appear in A) = ", count)
17+
18+
# calculate the position of each element in the sorted array
19+
for i in range(1, len(count)):
20+
count[i] = count[i] + count[i-1]
21+
22+
print("Counting array (storing order of elements appear in A) = ", count)
23+
24+
# store the elements back in result using the position of elements stored in count
25+
for i in range(len(A)-1, -1, -1):
26+
result[count[A[i]]-1] = A[i]
27+
count[A[i]] -= 1
28+
29+
return result
30+
31+
import random
32+
33+
# test function
34+
def test():
35+
while True:
36+
try:
37+
n = int(input("Enter length of array A (n): "))
38+
max_val = int(input("Enter the max val in A (smaller than n): "))
39+
40+
if max_val >= n:
41+
print("Invalid input.\n")
42+
43+
else:
44+
A = []
45+
46+
for _ in range(n):
47+
A.append(random.randint(0, max_val))
48+
49+
print("\nResult: ", counting_sort(A, max_val), "\n")
50+
51+
except Exception as e:
52+
print(e)
53+
print("Exiting...\n")
54+
break
55+
56+
if __name__ == "__main__":
57+
test()

0 commit comments

Comments
 (0)