-
Notifications
You must be signed in to change notification settings - Fork 359
/
Counting Sort.cpp
71 lines (54 loc) · 1.21 KB
/
Counting Sort.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//------ AI Programming ---------
// Counting Sort Algorithm
// Join our underground coding movement @freecodecs (c) June, 2019.
#include<iostream>
using namespace std;
int Max(int Arr[], int N){
int max = Arr[0];
for(int i=1; i<N; i++)
if(Arr[i] > max)
max = Arr[i];
return max;
}
int Min(int Arr[], int N){
int min = Arr[0];
for(int i=1; i<N; i++)
if(Arr[i] < min)
min = Arr[i];
return min;
}
void Print(int Arr[], int N){
for(int i=0; i<N; i++) cout<<Arr[i] <<", ";
}
int *Counting_Sort(int Arr[], int N){
int max = Max(Arr, N);
int min = Min(Arr, N);
int *Sorted_Arr = new int[N];
int *Count = new int[max-min+1];
for(int i=0; i<N; i++) Count[Arr[i]-min]++;
for(int i=1; i<(max-min+1); i++) Count[i]+=Count[i-1];
for(int i=N-1; i>=0; i--){
Sorted_Arr[Count[Arr[i]-min]-1] = Arr[i];
Count[Arr[i]-min]--;
}
return Sorted_Arr;
}
int main(){
int N;
cout<<"\nEnter size of elements:";
cin>>N;
int Arr[N];
for (int i = 0; i < N; ++i)
{
cout<<"\nEnter "<<i+1<<" element: ";
cin>>Arr[i];
}
int *Sorted_Arr;
cout<<"\nOrignal Elements : ";
Print(Arr, N);
Sorted_Arr = Counting_Sort(Arr, N);
cout<<"\nSorted Elements : ";
Print(Sorted_Arr, N);
cout<<endl;
return 0;
}