Skip to content

Commit a82fc0b

Browse files
committed
changes in counting sort
1 parent db12188 commit a82fc0b

File tree

1 file changed

+33
-14
lines changed

1 file changed

+33
-14
lines changed

sortingAlgo/countingSort/countingSort.py

Lines changed: 33 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,37 @@
1-
#TC
2-
arr = [10, 7, 8, 1, 4, 2, 5]
1+
'''COUNTINGSORT
2+
Counting sort is a sorting technique based on keys between a specific range.
3+
It works by counting the number of objects having distinct key values.
4+
Then doing some arithmetic to calculate the position of each object in the
5+
output sequence.'''
36

4-
def countingSort(arr, key=(lambda x:x), k=-1):
5-
if k==-1:
6-
k=max(arr)
7-
8-
table = [[] for _ in range(k+3)]
97

10-
for n in arr:
11-
table[key(n)].append(n)
8+
def countSort(arr):
9+
output = [0 for i in range(256)]
10+
count = [0 for i in range(256)] # Create a count array initialized with 0
11+
ans = ["" for _ in arr] # as strings are immutable
12+
13+
for i in arr:
14+
count[ord(i)] += 1 # position of character in the output array
15+
16+
17+
for i in range(256):
18+
count[i] += count[i-1] # output character array
19+
20+
21+
for i in range(len(arr)):
22+
output[count[ord(arr[i])]-1] = arr[i]
23+
count[ord(arr[i])] -= 1 # array of sorted charcters
24+
25+
26+
for i in range(len(arr)):
27+
ans[i] = output[i]
28+
return ans
29+
30+
31+
32+
#TEST
33+
arr = "Algorithms"
34+
ans = countSort(arr)
35+
print ("Sorted character array is "+str("".join(ans)))
1236

13-
arr = []
14-
for i in table:
15-
arr.extend(i)
16-
return arr
1737

18-
print(countingSort(arr, 15))

0 commit comments

Comments
 (0)