1 /*
2  * A fast, small, non-recursive O(nlog n) sort for the Linux kernel
3  *
4  * Jan 23 2005  Matt Mackall <mpm@selenic.com>
5  */
6 
7 #include <xen/types.h>
8 
u32_swap(void * a,void * b,int size)9 static void u32_swap(void *a, void *b, int size)
10 {
11     u32 t = *(u32 *)a;
12     *(u32 *)a = *(u32 *)b;
13     *(u32 *)b = t;
14 }
15 
generic_swap(void * a,void * b,int size)16 static void generic_swap(void *a, void *b, int size)
17 {
18     char t;
19 
20     do {
21         t = *(char *)a;
22         *(char *)a++ = *(char *)b;
23         *(char *)b++ = t;
24     } while ( --size > 0 );
25 }
26 
27 /*
28  * sort - sort an array of elements
29  * @base: pointer to data to sort
30  * @num: number of elements
31  * @size: size of each element
32  * @cmp: pointer to comparison function
33  * @swap: pointer to swap function or NULL
34  *
35  * This function does a heapsort on the given array. You may provide a
36  * swap function optimized to your element type.
37  *
38  * Sorting time is O(n log n) both on average and worst-case. While
39  * qsort is about 20% faster on average, it suffers from exploitable
40  * O(n*n) worst-case behavior and extra memory requirements that make
41  * it less suitable for kernel use.
42  */
43 
sort(void * base,size_t num,size_t size,int (* cmp)(const void *,const void *),void (* swap)(void *,void *,int size))44 void sort(void *base, size_t num, size_t size,
45           int (*cmp)(const void *, const void *),
46           void (*swap)(void *, void *, int size))
47 {
48     /* pre-scale counters for performance */
49     int i = (num/2 - 1) * size, n = num * size, c, r;
50 
51     if (!swap)
52         swap = (size == 4 ? u32_swap : generic_swap);
53 
54     /* heapify */
55     for ( ; i >= 0; i -= size )
56     {
57         for ( r = i; r * 2 + size < n; r  = c )
58         {
59             c = r * 2 + size;
60             if ( (c < n - size) && (cmp(base + c, base + c + size) < 0) )
61                 c += size;
62             if ( cmp(base + r, base + c) >= 0 )
63                 break;
64             swap(base + r, base + c, size);
65         }
66     }
67 
68     /* sort */
69     for ( i = n - size; i >= 0; i -= size )
70     {
71         swap(base, base + i, size);
72         for ( r = 0; r * 2 + size < i; r = c )
73         {
74             c = r * 2 + size;
75             if ( (c < i - size) && (cmp(base + c, base + c + size) < 0) )
76                 c += size;
77             if ( cmp(base + r, base + c) >= 0 )
78                 break;
79             swap(base + r, base + c, size);
80         }
81     }
82 }
83