Skip to content

Commit ff96fd8

Browse files
authored
added countSort.cpp
implementation of count sort in c++
1 parent 839613c commit ff96fd8

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

C++/countSort.cpp

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
void countsort(int arr[], int n)
4+
{
5+
int maxElement = arr[0];
6+
for (int i = 0; i < n; i++)
7+
{
8+
maxElement = max(maxElement, arr[i]);
9+
}
10+
11+
int count[10] = {0};
12+
for (int i = 0; i < n; i++)
13+
{
14+
count[arr[i]]++;
15+
}
16+
17+
for (int i = 1; i <= maxElement; i++)
18+
{
19+
count[i] += count[i - 1];
20+
}
21+
int output[n];
22+
for (int i = n - 1; i >= 0; i--)
23+
{
24+
output[--count[arr[i]]] = arr[i]; // take count of arr[i] and first decrement it
25+
}
26+
for (int i = 0; i < n; i++)
27+
{
28+
arr[i] = output[i];
29+
}
30+
}
31+
32+
int main()
33+
{
34+
int arr[] = {1, 3, 2, 3, 4, 1, 6, 4, 3};
35+
countsort(arr, 9);
36+
for (int i = 0; i < 9; i++)
37+
{
38+
cout << arr[i] << " ";
39+
}
40+
}

0 commit comments

Comments
 (0)