File tree Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Expand file tree Collapse file tree 1 file changed +32
-0
lines changed Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments