-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCounting Sort || Ascending & Descending order.cpp
90 lines (82 loc) · 2.18 KB
/
Counting Sort || Ascending & Descending order.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
//This Code for Ascendiong order Sort.
void printsortedarray(int arr[],int n){ //This function for printing sorted array.
for(int i=0; i<n; i++){
cout<<arr[i]<<" ";
}
}
void countsort(int arr[],int n){ //This function for sorting the array.
int maxvalue= -99999999;
int minvalue = 9999999;
for(int i=0; i<n; i++){
maxvalue = max(maxvalue,arr[i]);
minvalue = min(minvalue,arr[i]);
}
//1st step store the frequency
int offset = -minvalue; //making positive value of negavetive value
vector<int> freq(maxvalue-minvalue+1,0);
for(int i=0; i<n; i++){
freq[arr[i]+offset]++;
}
// placing the value at main array in correct order
int j =0;
for(int i=minvalue; i<=maxvalue; i++){
while(freq[i+offset]>0){
arr[j] = i;
freq[i+offset]--;
j++;
}
}
printsortedarray(arr,n);
}
int main(){
int arr[]= {5,4,1,2,3,-99};
int n=sizeof(arr)/sizeof(int);
countsort(arr,n);
return 0;
}
__________________________________________________________________________________________
__________________________________________________________________________________________
#include<iostream>
#include<cmath>
#include<vector>
using namespace std;
//This Code for descending order Sort.
void printsortedarray(int arr[],int n){ //This function for printing sorted array.
for(int i=0; i<n; i++){
cout<<arr[i]<<" ";
}
}
void countsort(int arr[],int n){ //This function for sorting the array.
int maxvalue= -99999999;
int minvalue = 9999999;
for(int i=0; i<n; i++){
maxvalue = max(maxvalue,arr[i]);
minvalue = min(minvalue,arr[i]);
}
//1st step store the frequency
int offset = -minvalue; //making positive value of negavetive value
vector<int> freq(maxvalue-minvalue+1,0);
for(int i=0; i<n; i++){
freq[arr[i]+offset]++;
}
// placing the value at main array in correct order
int j =0;
for(int i=maxvalue; i>=minvalue; i--){
while(freq[i+offset]>0){
arr[j] = i;
freq[i+offset]--;
j++;
}
}
printsortedarray(arr,n);
}
int main(){
int arr[]= {5,4,1,2,3,-99};
int n=sizeof(arr)/sizeof(int);
countsort(arr,n);
return 0;
}