Skip to content

Commit d16c253

Browse files
committed
add counting sort implementation
1 parent f13b476 commit d16c253

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
"""
2+
High level description:
3+
Counting sort is a sorting technique based on keys between a specific range,
4+
with efective performance on the predetermined range size of the values.
5+
It works by counting the number of objects having distinct key values (kind of hashing).
6+
Then doing some arithmetic to calculate the position of each object in the output sequence.
7+
8+
Time complexity:
9+
O(n+k) where n is the number of elements in input array and k is the range of input.
10+
11+
Auxiliary Space: O(n+k)
12+
"""
13+
14+
def counting_sort(arr):
15+
# Find min and max values
16+
min_value = min(arr)
17+
max_value = max(arr)
18+
19+
# Count number appearances in the array
20+
counting_arr = [0]*(max_value-min_value+1)
21+
for num in arr:
22+
counting_arr[num-min_value] += 1
23+
24+
# Rearrange sequence in the array
25+
index = 0
26+
for i, count in enumerate(counting_arr):
27+
for _ in range(count):
28+
arr[index] = min_value + i
29+
index += 1
30+
31+
test_array = [3, 3, 2, 6, 4, 7, 9, 7, 8]
32+
33+
counting_sort(test_array)
34+
35+
print(test_array)

0 commit comments

Comments
 (0)