Counting Sort problem in c++
I tried to write a counting sort algorithm in c++. But this program is not working. I tried to debug, but can't find the problem. Compiler shows no output(code is attached in the below). Can anyone tell me, What's going wrong in this code?
How can I fix this problem?
Thanks in advanced.
#include <bits/stdc++.h>
using namespace std;
void printArray(int a[], int n){
for(int i=0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<endl;
}
int main()
{
int n;
cin>>n;
int a[n];
for(int i=0;i<n;i++){
cin>>a[i];
}
cout<<"Before Sort: ";
printArray(a,n);
//step-1: Find Maximum
int max=INT_MIN;
for(int i=0;i<n;i++){
if(a[i]>max){
max=a[i];
}
}
//step-2: Initialization count+1 as 0
int count[max+1];
for(int i=0;i<=max;i++){
count[i]=0;
}
//step-3 Frequency calculation
for(int i=0;i<n;i++){
count[a[i]]++;
}
//step-4 Cumlative sum
for(int i=1;i<=max;i++){
count[i]+=count[i-1];
}
//step-5: Final array --> Backword traversal of basic array
int final[n];
for(int i=n-1;i>=0;i++){
count[a[i]]--;
int k=count[a[i]];
final[k]=a[i];
}
cout<<"After Sort: ";
printArray(final,n);
return 0;
}