forked from tanus786/CP-Codes-HackOctober-Fest-2023
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CountingSort.cpp
54 lines (54 loc) · 1.06 KB
/
CountingSort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include<iostream>
using namespace std;
void countingsort(int arr[], int r, int a)
{
int count[r]={0};
for(int i=0;i<a;i++)
{
count[arr[i]]++;
}
for(int i=1;i<r;i++)
{
count[i]+=count[i-1];
}
int oparr[a];
for(int i=0;i<a;i++)
{
oparr[--count[arr[i]]]=arr[i];
}
for(int i=0;i<a;i++)
{
arr[i]=oparr[i];
}
}
int main()
{
int a, r;
cout<<"Enter number of elements\n";
cin>>a;
cout<<"Enter the higher limit of range\n";
cin>>r;
system("cls");
int inparr[a];
cout<<"Enter the elements\n";
for(int i=0;i<a;i++)
{
while(1)
{
cout<<"Enter an element between 0 and "<<r<<endl;
cin>>inparr[i];
if(inparr[i]>=0&&inparr[i]<=r)
{
break;
}
}
}
countingsort(inparr, r, a);
cout<<"The sorted array is:\n";
for(int i=0;i<a;i++)
{
cout<<inparr[i]<<" ";
}
cout<<endl;
return 0;
}