-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCounting-Sort.cpp
72 lines (57 loc) · 1.52 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
61
62
63
64
65
66
67
68
69
70
71
72
#include<bits/stdc++.h>
using namespace std;
int totalNumberOfElements;
int maximumValue;
void printArray(int arr[], int arrLen)
{
for(int i=0; i<arrLen; i++)
{
cout << arr[i] << " ";
}
cout << endl;
}
void calculateFrequencyOf(int element[], int frequencyOf[])
{
//initialize frequency of all elements as 0
memset(frequencyOf, 0, (maximumValue+1)*sizeof(frequencyOf[0]));
//calculate the frequency
for(int i=0; i<totalNumberOfElements; i++)
{
frequencyOf[element[i]]++;
}
}
void countSort(int inputArray[], int frequencyOf[], int sortedArray[])
{
calculateFrequencyOf(inputArray, frequencyOf);
int i=0;
int totalOccurance;
for(int element=0; element<=maximumValue; element++)
{
totalOccurance = frequencyOf[element];
while(totalOccurance > 0)
{
sortedArray[i++] = element;
totalOccurance--;
}
}
}
int main()
{
//freopen("in.txt", "r", stdin);
cout << "Enter total number of elements: ";
cin >> totalNumberOfElements;
cout << "Enter maximum value of the input: ";
cin >> maximumValue;
int inputArray[totalNumberOfElements];
int frequencyArray[maximumValue+1];
int sortedArray[totalNumberOfElements];
cout << "Enter data: ";
for(int i=0; i<totalNumberOfElements; i++)
{
cin >> inputArray[i];
}
countSort(inputArray, frequencyArray, sortedArray);
puts("The sorted array:- ");
printArray(sortedArray, totalNumberOfElements);
return 0;
}