Saturday, 18 November 2017

C++ Program to Implement Counting Sort


Code:

#include  iostream

using namespace std;

// A function implementing Counter sort.
void CounterSort(int a[], int n, int r, int lower)
{
int i, j = 0, counter[r] = {0};
// Counting the number occurrence of each element.
for(i=0; i
counter[a[i]-lower]++;

i=0;
// placing the elements back into array.
while(i < r)
{
flag:
a[j] = lower+i;
j++;
counter[i]--;

// place the same element until its counter is zero.
if(counter[i] > 0)
goto flag;

i++;
}
}

int main()
{
int n, i, range, ulimit, llimit;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;

cout<<"\nEnter the lower and upper limit of the data to be entered: ";
cin>>llimit>>ulimit;

// Range of the input data. 
range = ulimit-llimit+1;

int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<
cin>>arr[i];
}

CounterSort(arr, n, range, llimit);

// Printing the sorted data.
cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
        cout<<"->"<

return 0;
}



Output:

Case 1:
Enter the number of data element to be sorted: 20

Enter the lower and upper limit of the data to be entered: 20 50
Enter element 1: 22
Enter element 2: 29
Enter element 3: 39
Enter element 4: 49
Enter element 5: 48
Enter element 6: 44
Enter element 7: 22
Enter element 8: 33
Enter element 9: 35
Enter element 10: 33
Enter element 11: 35
Enter element 12: 24
Enter element 13: 29
Enter element 14: 22
Enter element 15: 33
Enter element 16: 44
Enter element 17: 27
Enter element 18: 49
Enter element 19: 44
Enter element 20: 22

Sorted Data ->22->22->22->22->24->27->29->29->33->33->33->35->35->39->44->44->44->48->49->49


More C++ Programs:














100+ Best Home Decoration Ideas For Christmas Day 2019 To Make Home Beautiful

Best gifts for Christmas Day | Greeting cards for Christmas Day | Gift your children a new gift on Christmas day This Christmas d...