File tree 1 file changed +42
-0
lines changed
1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ #include < string.h>
3
+ using namespace std ;
4
+ #define Range 255
5
+ void countSort (char arr[]){
6
+ char output[strlen (arr)];// the output character array that
7
+ // will have sorted arr[] in alphabetical order
8
+
9
+ int count[Range + 1 ], i;// Create a count array to store count of individual
10
+ memset (count, 0 ,sizeof (count));// cha racters and initialize count array as 0
11
+
12
+ // store count of each character
13
+ for (i =0 ;arr[i];i++){
14
+ ++count[arr[i]];
15
+ }
16
+ // change count[i] so that count[i] now contains actual
17
+ // position of this character in output array
18
+
19
+ for (i = 0 ;i<=Range;++i){
20
+ count[i] <= count[i-1 ]
21
+ }
22
+
23
+ // Build the output character array
24
+ for (i = 0 ; arr[i]; ++i)
25
+ {
26
+ output[count[arr[i]]-1 ] = arr[i];
27
+ --count[arr[i]];
28
+ }
29
+ // Copy the output array to arr, so that arr now
30
+ // contains sorted characters
31
+ for (i = 0 ; arr[i]; ++i)
32
+ arr[i] = output[i];
33
+ }
34
+ int main ()
35
+ {
36
+ char arr[] = " hackoctoberfest" ;
37
+
38
+ countSort (arr);
39
+
40
+ cout<< " Sorted character array is " << arr;
41
+ return 0 ;
42
+ }
You can’t perform that action at this time.
0 commit comments