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/types.h>
8 #include <linux/export.h>
9 #include <linux/kernel.h>
10 #include <linux/sort.h>
12 static int alignment_ok(const void *base, int align)
14 return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ||
15 ((unsigned long)base & (align - 1)) == 0;
18 static void u32_swap(void *a, void *b, int size)
21 *(u32 *)a = *(u32 *)b;
25 static void u64_swap(void *a, void *b, int size)
28 *(u64 *)a = *(u64 *)b;
32 static void generic_swap(void *a, void *b, int size)
38 *(char *)a++ = *(char *)b;
44 * sort - sort an array of elements
45 * @base: pointer to data to sort
46 * @num: number of elements
47 * @size: size of each element
48 * @cmp_func: pointer to comparison function
49 * @swap_func: pointer to swap function or NULL
51 * This function does a heapsort on the given array. You may provide a
52 * swap_func function optimized to your element type.
54 * Sorting time is O(n log n) both on average and worst-case. While
55 * qsort is about 20% faster on average, it suffers from exploitable
56 * O(n*n) worst-case behavior and extra memory requirements that make
57 * it less suitable for kernel use.
60 void sort(void *base, size_t num, size_t size,
61 int (*cmp_func)(const void *, const void *),
62 void (*swap_func)(void *, void *, int size))
64 /* pre-scale counters for performance */
65 int i = (num/2 - 1) * size, n = num * size, c, r;
68 if (size == 4 && alignment_ok(base, 4))
70 else if (size == 8 && alignment_ok(base, 8))
73 swap_func = generic_swap;
77 for ( ; i >= 0; i -= size) {
78 for (r = i; r * 2 + size < n; r = c) {
81 cmp_func(base + c, base + c + size) < 0)
83 if (cmp_func(base + r, base + c) >= 0)
85 swap_func(base + r, base + c, size);
90 for (i = n - size; i > 0; i -= size) {
91 swap_func(base, base + i, size);
92 for (r = 0; r * 2 + size < i; r = c) {
95 cmp_func(base + c, base + c + size) < 0)
97 if (cmp_func(base + r, base + c) >= 0)
99 swap_func(base + r, base + c, size);
107 #include <linux/slab.h>
108 /* a simple boot-time regression test */
110 int cmpint(const void *a, const void *b)
112 return *(int *)a - *(int *)b;
115 static int sort_test(void)
119 a = kmalloc(1000 * sizeof(int), GFP_KERNEL);
122 printk("testing sort()\n");
124 for (i = 0; i < 1000; i++) {
125 r = (r * 725861) % 6599;
129 sort(a, 1000, sizeof(int), cmpint, NULL);
131 for (i = 0; i < 999; i++)
133 printk("sort() failed!\n");
142 module_init(sort_test);