From 242146a669550b7b93c1cf3403ad266e05895d30 Mon Sep 17 00:00:00 2001 From: Aman sharma <31547404+aman05382@users.noreply.github.com> Date: Mon, 21 Oct 2019 13:43:12 +0530 Subject: [PATCH] Counting_Sort in C++ --- codes/Counting_Sort.cpp | 64 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 codes/Counting_Sort.cpp diff --git a/codes/Counting_Sort.cpp b/codes/Counting_Sort.cpp new file mode 100644 index 0000000..0aabc54 --- /dev/null +++ b/codes/Counting_Sort.cpp @@ -0,0 +1,64 @@ +// C++ Program for counting sort +#include +#include +using namespace std; +#define RANGE 255 + +// The main function that sort +// the given string arr[] in +// alphabatical order +void countSort(char arr[]) +{ + // The output character array + // that will have sorted arr + char output[strlen(arr)]; + + // Create a count array to store count of inidividul + // characters and initialize count array as 0 + int count[RANGE + 1], i; + memset(count, 0, sizeof(count)); + + // Store count of each character + for(i = 0; arr[i]; ++i) + ++count[arr[i]]; + + // Change count[i] so that count[i] now contains actual + // position of this character in output array + for (i = 1; i <= RANGE; ++i) + count[i] += count[i-1]; + + // Build the output character array + for (i = 0; arr[i]; ++i) + { + output[count[arr[i]]-1] = arr[i]; + --count[arr[i]]; + } + + /* + For Stable algorithm + for (i = sizeof(arr)-1; i>=0; --i) + { + output[count[arr[i]]-1] = arr[i]; + --count[arr[i]]; + } + + For Logic : See implementation + */ + + // Copy the output array to arr, so that arr now + // contains sorted characters + for (i = 0; arr[i]; ++i) + arr[i] = output[i]; +} + +// Driver code +int main() +{ + char arr[] = "amansharma"; + + countSort(arr); + + cout<< "Sorted character array is " << arr; + return 0; +} +