// program to implement counting sort algorithm in c++
#include <iostream>
using namespace std;
void displayList(int elementList[], int length){
for(int index = 0; index < length; index++){
cout<<elementList[index]<<" ";
}
cout<<endl;
}
int* countingSort(int myList[], int length, int minElement, int maxElement){
// finding the length, min, max of the recieved list of numbers
int element;
// creating a count list with initial values as zeros
int countList[maxElement - minElement + 1];
for (int index = 0; index < (maxElement - minElement + 1); index++){
countList[index] = 0;
}
// counting number of times each element occurs in the list and storing the count in the coutList
for(int index = 0; index < length; index++) {
element = myList[index];
countList[element - minElement] = countList[element - minElement] + 1;
}
// starting from the min element upto max element
// we insert values according to their count in the new list in sorted order
element = minElement;
int index2 = 0;
for (int index = 0; index < (maxElement - minElement + 1); index++){
int Count = countList[index];
for(int j = 0; j < Count; j++) {
myList[index2] = element;
index2++;
}
element += 1;
}
return myList;
}
int main(){
int *sortedList;
cout<<"Program to implement counting sort algorithm in C++"<<endl;
int length, element;
cout<<"Enter the number of Elements to be sorted : ";
cin>>length;
int myList[length];
cout<<"Enter the elements to be sorted : ";
for(int index = 0; index < length; index++){
cin>>element;
myList[index] = element;
}
int minElement = myList[0], maxElement = myList[0];
for(int index = 0; index < length; index++){
if(minElement > myList[index]){
minElement = myList[index];
}
if(maxElement < myList[index]){
maxElement = myList[index];
}
}
cout<<"\\nThe list of elements before sorting is : "<<endl;
displayList(myList, length);
sortedList = countingSort(myList, length, minElement, maxElement);
cout<<"\\nThe sorted list is : "<<endl;
displayList(sortedList, length);
}