Skip to content

Commit f339719

Browse files
author
lowjack1
committedOct 16, 2019
add counting sort algorithm
1 parent edde17f commit f339719

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed
 

‎counting_sort.py

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
"""
2+
COUNTING SORT ALGORITHM
3+
4+
Assumption :
5+
1. Element of array should be integer
6+
2. Each integer should be in the range of [0, 10000000]
7+
8+
Time Complexity : O(max_value)
9+
Space Complexity : O(max_value)
10+
"""
11+
12+
def countingSort(unsorted_arr):
13+
""" Sort natural number by counting sort algorithm """
14+
max_value = max(unsorted_arr)
15+
# Create a count array kind of like the hash map of size max_value
16+
count = [0 for _ in range(max_value + 1)]
17+
for x in unsorted_arr:
18+
# Get the count of each element of the unsorted array
19+
count[x] += 1
20+
21+
# Store element in non-decreasing order
22+
sorted_arr = []
23+
for x in range(max_value+1):
24+
# Since we are iterating in ascending order, hence it is known for sure that
25+
# anay element which is going to append to the "sorted_arr" will be in sorted array
26+
for y in range(count[x]):
27+
sorted_arr.append(x)
28+
29+
return sorted_arr
30+
31+
# Get a list of integer from the user
32+
unsorted_arr = list(map(int, input().strip().split()))
33+
# Print sorted list of integer
34+
print(*countingSort(unsorted_arr))

0 commit comments

Comments
 (0)
Please sign in to comment.