C Fundamentals
Algorithms · data structures · cryptography · systems — pure C11, zero deps
Loading...
Searching...
No Matches
radix_sort.c
Go to the documentation of this file.
1/**
2 * @file radix_sort.c
3 * @brief LSD radix sort for non-negative ints, byte-by-byte.
4 *
5 * Uses 4 passes (one per byte of a 32-bit int) of stable counting sort.
6 * Linear in n × bytes — i.e. effectively O(n) when the value range is
7 * bounded. Operates on `unsigned int` internally to keep the byte
8 * extraction unambiguous; assumes input is non-negative.
9 *
10 * Returns silently without sorting if any value is negative — this is a
11 * teaching implementation, not a general-purpose replacement for quicksort.
12 */
13
14#include "sorts.h"
15#include <stdint.h>
16#include <stdlib.h>
17#include <string.h>
18
19#define RADIX_BUCKETS 256
20
21static void counting_pass(uint32_t *src, uint32_t *dst, size_t n, int byte_idx) {
22 size_t count[RADIX_BUCKETS] = {0};
23
24 for (size_t i = 0; i < n; i++) {
25 unsigned b = (unsigned)((src[i] >> (byte_idx * 8)) & 0xFF);
26 count[b]++;
27 }
28 for (int i = 1; i < RADIX_BUCKETS; i++) count[i] += count[i - 1];
29
30 /* Stable: walk source in reverse so equal keys preserve their order. */
31 for (size_t i = n; i > 0; i--) {
32 uint32_t v = src[i - 1];
33 unsigned b = (unsigned)((v >> (byte_idx * 8)) & 0xFF);
34 dst[--count[b]] = v;
35 }
36}
37
38void radix_sort_ints(int *arr, size_t n) {
39 if (n <= 1) return;
40
41 /* Reject negatives — this implementation is unsigned-only. */
42 for (size_t i = 0; i < n; i++) {
43 if (arr[i] < 0) return;
44 }
45
46 uint32_t *buf_a = malloc(n * sizeof(uint32_t));
47 uint32_t *buf_b = malloc(n * sizeof(uint32_t));
48 if (!buf_a || !buf_b) { free(buf_a); free(buf_b); return; }
49
50 for (size_t i = 0; i < n; i++) buf_a[i] = (uint32_t)arr[i];
51
52 counting_pass(buf_a, buf_b, n, 0);
53 counting_pass(buf_b, buf_a, n, 1);
54 counting_pass(buf_a, buf_b, n, 2);
55 counting_pass(buf_b, buf_a, n, 3);
56
57 for (size_t i = 0; i < n; i++) arr[i] = (int)buf_a[i];
58
59 free(buf_a);
60 free(buf_b);
61}
#define RADIX_BUCKETS
Definition radix_sort.c:19
static void counting_pass(uint32_t *src, uint32_t *dst, size_t n, int byte_idx)
Definition radix_sort.c:21
void radix_sort_ints(int *arr, size_t n)
Definition radix_sort.c:38
Unified header for all sorting algorithms.