forked from aditya-bijapurkar/Sorting-cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
countingSort.cpp
97 lines (74 loc) · 2.17 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
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
91
92
93
94
95
96
97
/*
COUNTING SORT!
Counting sort is a sorting technique based on keys between a specific range.
It works by counting the number of objects having distinct key values (kind of hashing).
Then doing some arithmetic to calculate the position of each object in the output sequence.
Time complexities:
O(n+k)
*/
#include <iostream>
using namespace std;
void countSort(int arr[], int n){
int max=arr[0];
for(int i=1;i<n;i++){
if(arr[i]>max){
max=arr[i];
}
}
int count[max+1]={0};
for(int i=0;i<n;i++){
count[arr[i]]++;
}
for(int i=1;i<=max;i++){
count[i]+=count[i-1];
}
int out[n+1];
for(int i=n-1;i>=0;i--){
out[--count[arr[i]]]=arr[i];
}
for(int i=0;i<n;i++){
arr[i]=out[i];
}
}
void printArray(int arr[], int size){
for(int i=0;i<size;i++){
cout<<arr[i]<<" ";
}
}
int main(){
int n;
cout<<"Enter the number of elements in the array: ";
cin>>n;
int arr[n];
//making an array
for(int i=0;i<n;i++){
cout<<"Enter the "<<i<<" element of the array: ";
cin>>arr[i];
}
cout<<"The given array is: ";
printArray(arr,n);
//calling the count-sort function
countSort(arr,n);
cout<<"\nThe Count Sorted array is: ";
printArray(arr, n);
return 0;
}
/*
Illustration:
given array: [9,3,2,1,5,1]
max=9
creating count array of 9+1 elements:
count = [0,0,0,0,0,0,0,0,0]
incrementing value of count array by travesing through given array:
count= [0,2,1,1,0,5,0,0,0,1]
adding count elements to the previous elements:
count= [0,2,3,4,4,9,9,9,9,10]
creating an output array of n+1 elements:
taking last element from given array and comparing its position from count array and placing it at that (location-1) in output array:
out=[1,1,2,3,5,5]
copying elements from out array in given array:
given=[1,1,2,3,5,5]
*/
/*
code written by Aditya Bijapurkar
*/