Skip to content

Commit 94d5021

Browse files
committed
Changed location of counting_sort.py
(i) Moved the file to sort/ folder (ii) Added new entry to README.md
1 parent da031f6 commit 94d5021

File tree

2 files changed

+47
-0
lines changed

2 files changed

+47
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,7 @@ Minimal and clean example implementations of data structures and algorithms in P
135135
- [sort_colors](sort/sort_colors.py)
136136
- [topsort](sort/topsort.py)
137137
- [wiggle_sort](sort/wiggle_sort.py)
138+
- [counting_sort](sort/counting_sort.py)
138139
- [stack](stack)
139140
- [longest_abs_path](stack/longest_abs_path.py)
140141
- [simplify_path](stack/simplify_path.py)

sort/counting_sort.py

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
def counting_sort(arr):
2+
"""
3+
Counting_sort
4+
Sorting a array which has no element greater than k
5+
Creating a new temp_arr,where temp_arr[i] contain the number of
6+
element less than or equal to i in the arr
7+
Then placing the number i into a correct position in the result_arr
8+
return the result_arr
9+
Complexity: 0(n)
10+
"""
11+
12+
m = min(arr)
13+
#in case there are negative elements, change the array to all positive element
14+
different = 0
15+
if m < 0:
16+
#save the change, so that we can convert the array back to all positive number
17+
different = -m
18+
for i in range (len(arr)):
19+
arr[i]+= -m
20+
k = max(arr)
21+
temp_arr = [0]*(k+1)
22+
for i in range(0,len(arr)):
23+
temp_arr[arr[i]] = temp_arr[arr[i]]+1
24+
#temp_array[i] contain the times the number i appear in arr
25+
26+
for i in range(1, k+1):
27+
temp_arr[i] = temp_arr[i] + temp_arr[i-1]
28+
#temp_array[i] contain the number of element less than or equal i in arr
29+
30+
result_arr = [0]*len(arr)
31+
#creating a result_arr an put the element in a correct positon
32+
for i in range(len(arr)-1,-1,-1):
33+
result_arr[temp_arr[arr[i]]-1] = arr[i]-different
34+
temp_arr[arr[i]] = temp_arr[arr[i]]-1
35+
36+
return result_arr
37+
38+
if __name__ == "__main__":
39+
positive_array = [1,2,3,4,9,1,2,8,3,5,7,0,9,8,1,7,4,5]
40+
negative_array = [-5,-6,-2,-3,-4,-5,0,-9,-2,-3,-8,-4]
41+
x = counting_sort(positive_array)
42+
y = counting_sort(negative_array)
43+
print(x)
44+
print(y)
45+
46+

0 commit comments

Comments
 (0)