2 * A fast, small, non-recursive O(nlog n) sort for the Linux kernel
4 * Jan 23 2005 Matt Mackall <mpm@selenic.com>
7 #include <linux/kernel.h>
8 #include <linux/module.h>
10 void u32_swap(void *a, void *b, int size)
13 *(u32 *)a = *(u32 *)b;
17 void generic_swap(void *a, void *b, int size)
23 *(char *)a++ = *(char *)b;
29 * sort - sort an array of elements
30 * @base: pointer to data to sort
31 * @num: number of elements
32 * @size: size of each element
33 * @cmp: pointer to comparison function
34 * @swap: pointer to swap function or NULL
36 * This function does a heapsort on the given array. You may provide a
37 * swap function optimized to your element type.
39 * Sorting time is O(n log n) both on average and worst-case. While
40 * qsort is about 20% faster on average, it suffers from exploitable
41 * O(n*n) worst-case behavior and extra memory requirements that make
42 * it less suitable for kernel use.
45 void sort(void *base, size_t num, size_t size,
46 int (*cmp)(const void *, const void *),
47 void (*swap)(void *, void *, int size))
49 /* pre-scale counters for performance */
50 int i = (num/2) * size, n = num * size, c, r;
53 swap = (size == 4 ? u32_swap : generic_swap);
56 for ( ; i >= 0; i -= size) {
57 for (r = i; r * 2 < n; r = c) {
59 if (c < n - size && cmp(base + c, base + c + size) < 0)
61 if (cmp(base + r, base + c) >= 0)
63 swap(base + r, base + c, size);
68 for (i = n - size; i >= 0; i -= size) {
69 swap(base, base + i, size);
70 for (r = 0; r * 2 < i; r = c) {
72 if (c < i - size && cmp(base + c, base + c + size) < 0)
74 if (cmp(base + r, base + c) >= 0)
76 swap(base + r, base + c, size);
84 /* a simple boot-time regression test */
86 int cmpint(const void *a, const void *b)
88 return *(int *)a - *(int *)b;
91 static int sort_test(void)
95 a = kmalloc(1000 * sizeof(int), GFP_KERNEL);
98 printk("testing sort()\n");
100 for (i = 0; i < 1000; i++) {
101 r = (r * 725861) % 6599;
105 sort(a, 1000, sizeof(int), cmpint, NULL);
107 for (i = 0; i < 999; i++)
109 printk("sort() failed!\n");
118 module_init(sort_test);