Skip to content

Instantly share code, notes, and snippets.

@0001vrn
Created August 16, 2016 08:17
Show Gist options
  • Save 0001vrn/0dc4491331a2753a0ecbce6d66566cbf to your computer and use it in GitHub Desktop.
Save 0001vrn/0dc4491331a2753a0ecbce6d66566cbf to your computer and use it in GitHub Desktop.
C++ program to implement Counting Sort
#include <iostream>
using namespace std;
void countingSort(int arr[],int n,int RANGE){
int count[RANGE]={0};
int i;
int out[n];
for(i=0;i<n;i++)
++count[arr[i]];
for(i=1;i<RANGE;i++)
count[i]+=count[i-1];
for(i=n-1;i>=0;i--){
out[count[arr[i]]-1]=arr[i];
--count[arr[i]];
}
for(i=0;i<n;i++)
arr[i]=out[i];
}
void print(int arr[],int n){
cout<<"array : ";
for(int i=0;i<n;i++)
cout<<arr[i]<<' ';
cout<<endl;
}
int main() {
// your code goes here
int arr[]={1, 4, 1, 2, 7, 5, 2};
int n=sizeof(arr)/sizeof(arr[0]);
int RANGE=9;
print(arr,n);
countingSort(arr,n,RANGE);
print(arr,n);
return 0;
}
@FemtoM
Copy link

FemtoM commented Oct 11, 2018

why can you made the array without using a constant? line 5
it works, but I have known that to make an array, you need to use constant values

@DucTrienDeveloper
Copy link

why RANGE = 9 ?
I wonder about that .
You want that ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment