File tree Expand file tree Collapse file tree 1 file changed +10
-12
lines changed Expand file tree Collapse file tree 1 file changed +10
-12
lines changed Original file line number Diff line number Diff line change 33
44using namespace std ;
55
6- void countSort (string arr) {
7- string output;
6+ void countSort (string& arr) {
7+ int n = arr.length ();
8+ string output (n, ' ' ); // pre-allocate space
89
9- int count[256 ], i ;
10- for (int i = 0 ; i < 256 ; i++) count[i] = 0 ;
10+ int count[256 ] = { 0 } ;
11+ for (int i = 0 ; i < n; ++i) ++ count[( unsigned char )arr[i]] ;
1112
12- for (i = 0 ; arr[i] ; ++i) ++ count[arr[i] ];
13+ for (int i = 1 ; i < 256 ; ++i) count[i] += count[i - 1 ];
1314
14- for (i = 1 ; i < 256 ; ++i) count[i] += count[i - 1 ];
15-
16- for (i = 0 ; arr[i]; ++i) {
17- output[count[arr[i]] - 1 ] = arr[i];
18- --count[arr[i]];
15+ for (int i = 0 ; i < n; ++i) {
16+ output[count[(unsigned char )arr[i]] - 1 ] = arr[i];
17+ --count[(unsigned char )arr[i]];
1918 }
2019
21- for (i = 0 ; arr[i]; ++i) arr[i] = output[i];
22-
20+ arr = output;
2321 cout << " Sorted character array is " << arr;
2422}
2523
You can’t perform that action at this time.
0 commit comments