Skip to content

Commit 4ffa897

Browse files
authored
Added counting sort
1 parent 2abee34 commit 4ffa897

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

Sorting/Counting_sort.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
def countSort(arr):
2+
3+
# The output character array that will have sorted arr
4+
output = [0 for i in range(256)]
5+
6+
# Create a count array to store count of inidividul
7+
# characters and initialize count array as 0
8+
count = [0 for i in range(256)]
9+
10+
# For storing the resulting answer since the
11+
# string is immutable
12+
ans = ["" for _ in arr]
13+
14+
# Store count of each character
15+
for i in arr:
16+
count[ord(i)] += 1
17+
18+
# Change count[i] so that count[i] now contains actual
19+
# position of this character in output array
20+
for i in range(256):
21+
count[i] += count[i-1]
22+
23+
# Build the output character array
24+
for i in range(len(arr)):
25+
output[count[ord(arr[i])]-1] = arr[i]
26+
count[ord(arr[i])] -= 1
27+
28+
# Copy the output array to arr, so that arr now
29+
# contains sorted characters
30+
for i in range(len(arr)):
31+
ans[i] = output[i]
32+
return ans

0 commit comments

Comments
 (0)