Skip to content

Commit 87ec985

Browse files
authored
Merge pull request AllAlgorithms#203 from kavya98527/patch-1
Create counting_sort.cpp
2 parents 3d26eaa + fcc772b commit 87ec985

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed

sorting/counting_sort.cpp

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#include<iostream>
2+
3+
using namespace std;
4+
5+
// A function implementing Counter sort.
6+
void CounterSort(int a[], int n, int r, int lower)
7+
{
8+
int i, j = 0, counter[r] = {0};
9+
// Counting the number occurrence of each element.
10+
for(i=0; i<n; i++)
11+
counter[a[i]-lower]++;
12+
13+
i=0;
14+
// placing the elements back into array.
15+
while(i < r)
16+
{
17+
flag:
18+
a[j] = lower+i;
19+
j++;
20+
counter[i]--;
21+
22+
// place the same element until its counter is zero.
23+
if(counter[i] > 0)
24+
goto flag;
25+
26+
i++;
27+
}
28+
}
29+
30+
int main()
31+
{
32+
int n, i, range, ulimit, llimit;
33+
cout<<"\nEnter the number of data element to be sorted: ";
34+
cin>>n;
35+
36+
cout<<"\nEnter the lower and upper limit of the data to be entered: ";
37+
cin>>llimit>>ulimit;
38+
39+
// Range of the input data.
40+
range = ulimit-llimit+1;
41+
42+
int arr[n];
43+
for(i = 0; i < n; i++)
44+
{
45+
cout<<"Enter element "<<i+1<<": ";
46+
cin>>arr[i];
47+
}
48+
49+
CounterSort(arr, n, range, llimit);
50+
51+
// Printing the sorted data.
52+
cout<<"\nSorted Data ";
53+
for (i = 0; i < n; i++)
54+
cout<<"->"<<arr[i];
55+
56+
return 0;
57+
}

0 commit comments

Comments
 (0)