File tree 1 file changed +43
-0
lines changed
1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ # Python program for counting sort
2
+
3
+ # The main function that sort the given string arr[] in
4
+ # 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 individual
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 = input ("enter any array:" )
40
+ ans = countSort (arr )
41
+ print ("Sorted character array is %s" % ("" .join (ans )))
42
+
43
+ # This code is contributed by Nikhil Kumar Singh
You can’t perform that action at this time.
0 commit comments