-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcount_sort.cpp
72 lines (60 loc) · 1.52 KB
/
count_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
61
62
63
64
65
66
67
68
69
70
71
72
#include <bits/stdc++.h>
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 k=array[1];
for(int i=0;i<size;i++){
k=max(k,array[i]);
}
//int max = getMax(array, size);
int count[k + 1]; // create count array (max+1 number of elements)
for (int i = 0; i <= k; i++)
count[i] = 0; // initialize count array to all zero
for (int i = 1; i <= size; i++)
count[array[i]]++; // increase number count in count array.
for (int i = 1; i <= k; i++)
count[i] += count[i - 1]; // find cumulative frequency
for (int i = size; i >= 1; i--)
{
output[count[array[i]]] = array[i];
count[array[i]] -= 1; // decrease count for same numbers
}
for (int i = 1; i <= size; i++)
{
array[i] = output[i]; // store output array to main array
}
}
int main()
{
int n;
cout << "Enter the number of elements number?: "<<endl;;
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);
}