diff --git a/CountingSort/CountSort.cpp b/CountingSort/CountSort.cpp new file mode 100644 index 0000000..8c47f95 --- /dev/null +++ b/CountingSort/CountSort.cpp @@ -0,0 +1,32 @@ +#include +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 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 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; +} diff --git a/CountingSort/README.md b/CountingSort/README.md new file mode 100644 index 0000000..89f9c56 --- /dev/null +++ b/CountingSort/README.md @@ -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.