-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathcountingsort.cpp
More file actions
49 lines (49 loc) · 1.19 KB
/
countingsort.cpp
File metadata and controls
49 lines (49 loc) · 1.19 KB
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
#include<iostream>
#include<algorithm>
using namespace std;
void display(int *array, int size) {
for(int i = 1; i<=size; i++)
cout << array[i] << " ";
cout << endl;
}
int getMax(int array[], int size) {
int max = array[1];
for(int i = 2; i<=size; i++) {
if(array[i] > max)
max = array[i];
}
return max;
}
void countSort(int *array, int size) {
int output[size+1];
int max = getMax(array, size);
int count[max+1];
for(int i = 0; i<=max; i++)
count[i] = 0;
for(int i = 1; i <=size; i++)
count[array[i]]++;
for(int i = 1; i<=max; i++)
count[i] += count[i-1];
for(int i = size; i>=1; i--) {
output[count[array[i]]] = array[i];
count[array[i]] -= 1;
}
for(int i = 1; i<=size; i++) {
array[i] = output[i];
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n+1];
cout << "Enter elements:" << endl;
for(int i = 1; i<=n; i++) {
cin >> arr[i];
}
cout << "Array before Sorting: ";
display(arr, n);
countSort(arr, n);
cout << "Array after Sorting: ";
display(arr, n);
}