C Online Compiler
Example: Counting Sort Implementation in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Counting Sort Implementation #include <stdio.h> #include <stdlib.h> // For malloc and free // Function to find the maximum element in an array int findMax(int arr[], int n) { int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) { max = arr[i]; } } return max; } // Function to implement Counting Sort void countingSort(int arr[], int n) { // Step 1: Find the maximum element in the input array int max = findMax(arr, n); // Step 2: Create a count array to store the frequency of each element // The size of count array will be max + 1 (for 0 to max) int *count = (int *)calloc(max + 1, sizeof(int)); if (count == NULL) { printf("Memory allocation failed for count array.\n"); return; } // Step 3: Create an output array to store the sorted elements int *output = (int *)malloc(n * sizeof(int)); if (output == NULL) { printf("Memory allocation failed for output array.\n"); free(count); // Clean up already allocated memory return; } // Step 4: Store the count of each element for (int i = 0; i < n; i++) { count[arr[i]]++; } // Step 5: Modify the count array to store the actual position // of each element in the output array. // This accumulates the counts, so count[i] now stores the number // of elements less than or equal to i. for (int i = 1; i <= max; i++) { count[i] += count[i - 1]; } // Step 6: Build the output array // Iterate from the end of the input array to maintain stability // (if elements are equal, their relative order is preserved). for (int i = n - 1; i >= 0; i--) { output[count[arr[i]] - 1] = arr[i]; count[arr[i]]--; // Decrement the count for the current element } // Step 7: Copy the sorted elements from the output array back to the original array for (int i = 0; i < n; i++) { arr[i] = output[i]; } // Step 8: Free the dynamically allocated memory free(count); free(output); } // Utility function to print an array void printArray(int arr[], int n) { for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } printf("\n"); } int main() { // Example array to be sorted int arr[] = {4, 2, 2, 8, 3, 3, 1, 0, 9, 5}; int n = sizeof(arr) / sizeof(arr[0]); printf("Original array: "); printArray(arr, n); // Apply Counting Sort countingSort(arr, n); printf("Sorted array: "); printArray(arr, n); return 0; }
Output
Clear
ADVERTISEMENTS