void countingSort(int arr[], int n) { int output[n]; int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } int count[max + 1]; for (int i = 0; i <= max; i++) count[i] = 0; for (int i = 0; i < n; i++) count[arr[i]]++; for (int i = 1; i <= max; i++) count[i] += count[i - 1]; for (int i = n - 1; i >= 0; i--) { output[count[arr[i]] - 1] = arr[i]; count[arr[i]]--; } for (int i = 0; i < n; i++) arr[i] = output[i]; } int main() { int arr[] = {4, 2, 2, 8, 3, 3, 1}; int n = sizeof(arr) / sizeof(arr[0]); countingSort(arr, n); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
Counting Sort counts how many times each number appears, then uses that to place numbers in sorted order. The output is the sorted array: 1 2 2 3 3 4 8.
Comparison based sorting algorithms cannot do better than O(n log n) on average due to decision tree limits. Non comparison based algorithms like Counting Sort or Radix Sort can achieve O(n) if input constraints allow.
void countingSortForRadix(int arr[], int n, int exp) { int output[n]; int count[10] = {0}; for (int i = 0; i < n; i++) count[(arr[i] / exp) % 10]++; for (int i = 1; i < 10; i++) count[i] += count[i - 1]; for (int i = n - 1; i >= 0; i--) { output[count[(arr[i] / exp) % 10] - 1] = arr[i]; count[(arr[i] / exp) % 10]--; } for (int i = 0; i < n; i++) arr[i] = output[i]; } int main() { int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; int n = sizeof(arr) / sizeof(arr[0]); int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } for (int exp = 1; max / exp > 0; exp *= 10) { countingSortForRadix(arr, n, exp); } for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
The code correctly implements Radix Sort using Counting Sort as a subroutine. It sorts the array properly without errors.
int partition(int arr[], int low, int high) { int pivot = arr[high]; int i = low - 1; for (int j = low; j <= high - 1; j++) { if (arr[j] < pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } int main() { int arr[] = {10, 7, 8, 9, 1, 5}; int n = sizeof(arr) / sizeof(arr[0]); int pi = partition(arr, 0, n - 1); for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0; }
After partition, elements less than pivot (5) are moved left, pivot placed at correct position index 1. The array becomes: 1 5 8 9 10 7.
Non comparison based sorts like Counting Sort require the input to be integers in a limited range to count frequencies. Arbitrary data types like floats or strings don't fit this requirement easily.
