forked from Midway91/HactoberFest2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcounting_sort.cpp
60 lines (41 loc) · 1.25 KB
/
counting_sort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
#include <bits/stdc++.h>
using namespace std;
vector<int> countSort(vector<int>& inputArray)
{
int N = inputArray.size();
// Finding the maximum element of array inputArray[].
int M = 0;
for (int i = 0; i < N; i++)
M = max(M, inputArray[i]);
// Initializing countArray[] with 0
vector<int> countArray(M + 1, 0);
// Mapping each element of inputArray[] as an index
// of countArray[] array
for (int i = 0; i < N; i++)
countArray[inputArray[i]]++;
// Calculating prefix sum at every index
// of array countArray[]
for (int i = 1; i <= M; i++)
countArray[i] += countArray[i - 1];
// Creating outputArray[] from countArray[] array
vector<int> outputArray(N);
for (int i = N - 1; i >= 0; i--)
{
outputArray[countArray[inputArray[i]] - 1]
= inputArray[i];
countArray[inputArray[i]]--;
}
return outputArray;
}
// Driver code
int main()
{
// Input array
vector<int> inputArray = { 4, 3, 12, 1, 5, 5, 3, 9 };
// Output array
vector<int> outputArray = countSort(inputArray);
for (int i = 0; i < inputArray.size(); i++)
cout << outputArray[i] << " ";
return 0;
}
#contributed by debasmita1701