Skip to content

Commit 0c1bdb5

Browse files
Merge pull request #290 from ameybhosle1/master
countingsort
2 parents c3d9f8c + d1c1508 commit 0c1bdb5

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

countingsort.cpp

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
#include<bits/stdc++.h>
2+
#include<string.h>
3+
using namespace std;
4+
#define RANGE 255
5+
6+
// The main function that sort
7+
// the given string arr[] in
8+
// alphabatical order
9+
void countSort(char arr[])
10+
{
11+
// The output character array
12+
// that will have sorted arr
13+
char output[strlen(arr)];
14+
15+
// Create a count array to store count of inidividul
16+
// characters and initialize count array as 0
17+
int count[RANGE + 1], i;
18+
memset(count, 0, sizeof(count));
19+
20+
// Store count of each character
21+
for(i = 0; arr[i]; ++i)
22+
++count[arr[i]];
23+
24+
// Change count[i] so that count[i] now contains actual
25+
// position of this character in output array
26+
for (i = 1; i <= RANGE; ++i)
27+
count[i] += count[i-1];
28+
29+
// Build the output character array
30+
for (i = 0; arr[i]; ++i)
31+
{
32+
output[count[arr[i]]-1] = arr[i];
33+
--count[arr[i]];
34+
}
35+
36+
/*
37+
For Stable algorithm
38+
for (i = sizeof(arr)-1; i>=0; --i)
39+
{
40+
output[count[arr[i]]-1] = arr[i];
41+
--count[arr[i]];
42+
}
43+
44+
For Logic : See implementation
45+
*/
46+
47+
// Copy the output array to arr, so that arr now
48+
// contains sorted characters
49+
for (i = 0; arr[i]; ++i)
50+
arr[i] = output[i];
51+
}
52+
53+
// Driver code
54+
int main()
55+
{
56+
char arr[] = "geeksforgeeks";
57+
58+
countSort(arr);
59+
60+
cout<< "Sorted character array is " << arr;
61+
return 0;
62+
}

0 commit comments

Comments
 (0)