-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCounting-sort.cpp
60 lines (53 loc) · 1.4 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
// Counting sort is a stable sorting technique,
// which is used to sort objects according the keys that are small
// numbers.It counts the number of keys whose key values are
// same.This sorting technique is efficient when difference between
// different keys are not so big,
// otherwise it can increase the space complexity.
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int getMax(int* arr, int n) {
int max_ = arr[1];
for (int i = 2; i <= n; i++) {
if (arr[i] > max_) {
max_ = arr[i];
}
}
return max_;
}
void CountingSort(int* arr, int n) {
int max_ele = getMax(arr, n);
int count[max_ele + 1];
int output[n + 1];
for (int i = 0; i <= max_ele; i++) {
count[i] = 0;
}
for (int i = 1; i <= n; i++) {
count[arr[i]]++;
}
for (int i = 1; i <= max_ele; i++) {
count[i] += count[i - 1];
}
for (int i = n ; i >= 1; i--) {
output[count[arr[i]]] = arr[i];
count[arr[i]]--;
}
for (int i = 1; i <= n; i++) {
arr[i] = output[i];
}
}
void PrintArray(int* arr, int n) {
cout << "Sorted array is \n";
for (int i = 1; i <= n; i++)
cout << arr[i] << " ";
std::cout << std::endl;
}
int main(int argc, const char **argv) {
int arr[] = {0, 10, 12, 4, 8, 4, 6, 7, 8, 9, 0, 1, 15};
int n = sizeof(arr)/sizeof(arr[0])-1;
CountingSort(arr, n);
PrintArray(arr, n);
return 0;
}