From 32f64e5d7d7a74fac12186ef58c06e68f30fba3e Mon Sep 17 00:00:00 2001 From: unknown <19uec026@lnmiit.ac.in> Date: Thu, 31 Oct 2019 19:52:30 +0530 Subject: [PATCH] added counting sort algo in c --- Sorting/CountingSort.c | 61 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 Sorting/CountingSort.c diff --git a/Sorting/CountingSort.c b/Sorting/CountingSort.c new file mode 100644 index 0000000..6cbe70c --- /dev/null +++ b/Sorting/CountingSort.c @@ -0,0 +1,61 @@ +// C Program for counting sort +#include +#include +#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 program to test above function +int main() +{ + char arr[] = "geeksforgeeks";//"applepp"; + + countSort(arr); + + printf("Sorted character array is %sn", arr); + return 0; +} +