From e61ea610db81603e6a80477b5fa6aa8f7a9416a2 Mon Sep 17 00:00:00 2001 From: Raj Mhetar Date: Fri, 18 Oct 2024 12:52:48 +0530 Subject: [PATCH] added CountSort Alogorithm in c++ --- Sorting/CountSort.cpp | 60 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 Sorting/CountSort.cpp diff --git a/Sorting/CountSort.cpp b/Sorting/CountSort.cpp new file mode 100644 index 00000000..38716163 --- /dev/null +++ b/Sorting/CountSort.cpp @@ -0,0 +1,60 @@ +#include +#include +#include +using namespace std; + +// Function to perform counting sort +void countSort(vector &arr) +{ + // Find the minimum and maximum element in the array + int maxElement = *max_element(arr.begin(), arr.end()); + int minElement = *min_element(arr.begin(), arr.end()); + + // Size of the range + int range = maxElement - minElement + 1; + + // Create a count array to store the frequency of each element in the range + vector count(range, 0); + + // Store the count of each element in the count array + for (int i = 0; i < arr.size(); i++) + { + count[arr[i] - minElement]++; + } + + // Overwrite the original array with sorted elements using the count array + int index = 0; + for (int i = 0; i < range; i++) + { + while (count[i] > 0) + { + arr[index++] = i + minElement; + count[i]--; + } + } +} + +// Helper function to print the array +void printArray(const vector &arr) +{ + for (int num : arr) + { + cout << num << " "; + } + cout << endl; +} + +int main() +{ + vector arr = {4, -2, 2, 8, 3, -3, 1}; + + cout << "Original array: "; + printArray(arr); + + countSort(arr); + + cout << "Sorted array: "; + printArray(arr); + + return 0; +}