From b32e8189de215aea47dbd3c45e6eb8361a022972 Mon Sep 17 00:00:00 2001 From: Kumar Vikram Date: Sat, 16 Feb 2019 17:00:18 +0530 Subject: [PATCH] Added Counting sort in C++ --- Sorting/Counting Sort/C++/CountingSort.cpp | 38 ++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Sorting/Counting Sort/C++/CountingSort.cpp diff --git a/Sorting/Counting Sort/C++/CountingSort.cpp b/Sorting/Counting Sort/C++/CountingSort.cpp new file mode 100644 index 00000000..14b38f9b --- /dev/null +++ b/Sorting/Counting Sort/C++/CountingSort.cpp @@ -0,0 +1,38 @@ +//Counting sort which takes negative numbers as well +//Using c++ 17 +#include +#include +#include + +void countSort(std::vector & arr) { + auto [min, max] = std::minmax_element(arr.begin(), arr.end()); + int range = (*max) - (*min) + 1; + + std::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]; +} + +void printArray(std::vector & arr) { + for (int i=0; i < arr.size(); i++) + std::cout << arr[i] << " \n"[i==arr.size()-1]; +} + +int main() { + std::vector arr = {-5, -10, 0, -3, 8, 5, -1, 10}; + countSort (arr); + printArray (arr); + return 0; +} \ No newline at end of file