TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
counting_sort.cpp
1#include <iostream>
2using namespace std;
3
4int Max(int Arr[], int N) {
5 int max = Arr[0];
6 for (int i = 1; i < N; i++)
7 if (Arr[i] > max)
8 max = Arr[i];
9 return max;
10}
11
12int Min(int Arr[], int N) {
13 int min = Arr[0];
14 for (int i = 1; i < N; i++)
15 if (Arr[i] < min)
16 min = Arr[i];
17 return min;
18}
19
20void Print(int Arr[], int N) {
21 for (int i = 0; i < N; i++) cout << Arr[i] << ", ";
22}
23
24int *Counting_Sort(int Arr[], int N) {
25 int max = Max(Arr, N);
26 int min = Min(Arr, N);
27 int *Sorted_Arr = new int[N];
28
29 int *Count = new int[max - min + 1];
30 for (int i = 0; i < max - min + 1; ++i) {
31 Count[i] = 0;
32 }
33
34 for (int i = 0; i < N; i++) Count[Arr[i] - min]++;
35
36 for (int i = 1; i < (max - min + 1); i++) Count[i] += Count[i - 1];
37
38 for (int i = N - 1; i >= 0; i--) {
39 Sorted_Arr[Count[Arr[i] - min] - 1] = Arr[i];
40 Count[Arr[i] - min]--;
41 }
42
43 delete[] Count;
44 return Sorted_Arr;
45}
46
47int main() {
48 int Arr[] = {47, 65, 20, 66, 25, 53, 64, 69, 72, 22,
49 74, 25, 53, 15, 42, 36, 4, 69, 86, 19},
50 N = 20;
51 int *Sorted_Arr;
52
53 cout << "\n\tOrignal Array = ";
54 Print(Arr, N);
55 Sorted_Arr = Counting_Sort(Arr, N);
56 cout << "\n\t Sorted Array = ";
57 Print(Sorted_Arr, N);
58 delete[] Sorted_Arr;
59 cout << endl;
60
61 return 0;
62}
int main()
Main function.
#define endl
constexpr uint32_t N
A struct to represent sparse table for min() as their invariant function, for the given array A....