Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions CountingSort/CountSort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
#include<bits/stdc++.h>
using namespace std;
#define ln "\n";
#define TC() int t; cin >> t; while(t--)
#define IO() ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)

int main(){

vector<int> arr = {1,4,1,2,7,5,2};
int max = *max_element(arr.begin(), arr.end());
int min = *min_element(arr.begin(), arr.end());
int range = max - min + 1;

vector<int> count(range), output(arr.size());
for (int i = 0; i < arr.size(); i++)
count[arr[i] - min]++;

for (int i = 1; i < count.size(); i++)
count[i] += count[i - 1];

for (int i = arr.size() - 1; i >= 0; i--) {
output[count[arr[i] - min] - 1] = arr[i];
count[arr[i] - min]--;
}

for (int i = 0; i < arr.size(); i++)
arr[i] = output[i];

for(auto i : arr) cout << i << " ";

return 0;
}
2 changes: 2 additions & 0 deletions CountingSort/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Counting sort is a sorting method which is used to sort the given array in linear time. It works like hashing technique,
where it counts the number of objects having distinct key values and does some prefix sum calculations and finds the position of each object in the output sequence.