Created
August 16, 2016 08:17
-
-
Save 0001vrn/0dc4491331a2753a0ecbce6d66566cbf to your computer and use it in GitHub Desktop.
C++ program to implement Counting Sort
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
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
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