-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
613998c
commit d0b460f
Showing
1 changed file
with
64 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
// C++ Program for counting sort | ||
#include <bits/stdc++.h> | ||
#include <string.h> | ||
using namespace std; | ||
#define RANGE 255 | ||
|
||
// The main function that sort | ||
// the given string arr[] in | ||
// alphabetical order | ||
void countSort(char arr[]) | ||
{ | ||
// The output character array | ||
// that will have sorted arr | ||
char output[strlen(arr)]; | ||
|
||
// Create a count array to store count of individual | ||
// characters and initialize count array as 0 | ||
int count[RANGE + 1], i; | ||
memset(count, 0, sizeof(count)); | ||
|
||
// Store count of each character | ||
for (i = 0; arr[i]; ++i) | ||
++count[arr[i]]; | ||
|
||
// Change count[i] so that count[i] now contains actual | ||
// position of this character in output array | ||
for (i = 1; i <= RANGE; ++i) | ||
count[i] += count[i - 1]; | ||
|
||
// Build the output character array | ||
for (i = 0; arr[i]; ++i) { | ||
output[count[arr[i]] - 1] = arr[i]; | ||
--count[arr[i]]; | ||
} | ||
|
||
/* | ||
For Stable algorithm | ||
for (i = sizeof(arr)-1; i>=0; --i) | ||
{ | ||
output[count[arr[i]]-1] = arr[i]; | ||
--count[arr[i]]; | ||
} | ||
For Logic : See implementation | ||
*/ | ||
|
||
// Copy the output array to arr, so that arr now | ||
// contains sorted characters | ||
for (i = 0; arr[i]; ++i) | ||
arr[i] = output[i]; | ||
} | ||
|
||
// Driver code | ||
int main() | ||
{ | ||
char arr[] = "geeksforgeeks"; | ||
|
||
countSort(arr); | ||
|
||
cout << "Sorted character array is " << arr; | ||
return 0; | ||
} | ||
|
||
// This code is contributed by rathbhupendra |