Skip to content

Commit 14e6372

Browse files
authored
Added counting sort in python
1 parent 3ecb193 commit 14e6372

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

sorts/countingsort.py

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
# Python program for counting sort
2+
3+
# This is the main function that sort the given string arr[] in
4+
# in the alphabetical order
5+
def countSort(arr):
6+
7+
# The output character array that will have sorted arr
8+
output = [0 for i in range(256)]
9+
10+
# Create a count array to store count of inidividul
11+
# characters and initialize count array as 0
12+
count = [0 for i in range(256)]
13+
14+
# For storing the resulting answer since the
15+
# string is immutable
16+
ans = ["" for _ in arr]
17+
18+
# Store count of each character
19+
for i in arr:
20+
count[ord(i)] += 1
21+
22+
# Change count[i] so that count[i] now contains actual
23+
# position of this character in output array
24+
for i in range(256):
25+
count[i] += count[i-1]
26+
27+
# Build the output character array
28+
for i in range(len(arr)):
29+
output[count[ord(arr[i])]-1] = arr[i]
30+
count[ord(arr[i])] -= 1
31+
32+
# Copy the output array to arr, so that arr now
33+
# contains sorted characters
34+
for i in range(len(arr)):
35+
ans[i] = output[i]
36+
return ans
37+
38+
# Driver program to test above function
39+
arr = "thisisthestring"
40+
ans = countSort(arr)
41+
print ("Sorted string array is %s" %("".join(ans)))

0 commit comments

Comments
 (0)