2 * Sherlock Library -- Universal Array Sorter
4 * (c) 2003 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
11 * This is not a normal header file, it's a generator of sorting
12 * routines. Each time you include it with parameters set in the
13 * corresponding preprocessor macros, it generates an array sorter
14 * with the parameters given.
16 * You might wonder why the heck do we implement our own array sorter
17 * instead of using qsort(). The primary reason is that qsort handles
18 * only continuous arrays, but we need to sort array-like data structures
19 * where the only way to access elements is by using an indexing macro.
20 * Besides that, we are more than 2 times faster.
22 * So much for advocacy, there are the parameters (those marked with [*]
25 * ASORT_PREFIX(x) [*] add a name prefix (used on all global names
26 * defined by the sorter)
27 * ASORT_KEY_TYPE [*] data type of a single array entry key
28 * ASORT_ELT(i) [*] returns the key of i-th element
29 * ASORT_LT(x,y) x < y for ASORT_TYPE (default: "x<y")
30 * ASORT_SWAP(i,j) swap i-th and j-th element (default: assume _ELT
31 * is a l-value and swap just the keys)
32 * ASORT_THRESHOLD threshold for switching between quicksort and insertsort
34 * After including this file, a function ASORT_PREFIX(sort)(uns array_size)
35 * is declared and all parameter macros are automatically undef'd.
39 #define ASORT_LT(x,y) ((x) < (y))
43 #define ASORT_SWAP(i,j) do { ASORT_KEY_TYPE tmp = ASORT_ELT(i); ASORT_ELT(i)=ASORT_ELT(j); ASORT_ELT(j)=tmp; } while (0)
46 #ifndef ASORT_THRESHOLD
47 #define ASORT_THRESHOLD 8 /* Guesswork and experimentation */
50 static void ASORT_PREFIX(sort)(uns array_size)
52 struct stk { int l, r; } stack[8*sizeof(uns)];
53 int l, r, left, right, m;
60 /* QuickSort with optimizations a'la Sedgewick, but stop at ASORT_THRESHOLD */
63 right = array_size - 1;
69 if (ASORT_LT(ASORT_ELT(m), ASORT_ELT(l)))
71 if (ASORT_LT(ASORT_ELT(r), ASORT_ELT(m)))
74 if (ASORT_LT(ASORT_ELT(m), ASORT_ELT(l)))
80 while (ASORT_LT(ASORT_ELT(l), pivot))
82 while (ASORT_LT(pivot, ASORT_ELT(r)))
97 if ((r - left) > ASORT_THRESHOLD && (right - l) > ASORT_THRESHOLD)
99 /* Both partitions ok => push the larger one */
100 if ((r - left) > (right - l))
114 else if ((r - left) > ASORT_THRESHOLD)
116 /* Left partition OK, right undersize */
119 else if ((right - l) > ASORT_THRESHOLD)
121 /* Right partition OK, left undersize */
126 /* Both partitions undersize => pop */
136 * We have a partially sorted array, finish by insertsort. Inspired
137 * by qsort() in GNU libc.
140 /* Find minimal element which will serve as a barrier */
141 r = MIN(array_size, ASORT_THRESHOLD);
144 if (ASORT_LT(ASORT_ELT(l),ASORT_ELT(m)))
149 for (m=1; m<(int)array_size; m++)
152 while (ASORT_LT(ASORT_ELT(m),ASORT_ELT(l-1)))
167 #undef ASORT_THRESHOLD