src/stdlib/SDL_qsort.c
author Sam Lantinga <slouken@libsdl.org>
Mon, 29 May 2006 04:04:35 +0000
branchSDL-1.3
changeset 1668 4da1ee79c9af
parent 1662 782fd950bd46
permissions -rw-r--r--
more tweaking indent options
     1 /* qsort.c
     2  * (c) 1998 Gareth McCaughan
     3  *
     4  * This is a drop-in replacement for the C library's |qsort()| routine.
     5  *
     6  * Features:
     7  *   - Median-of-three pivoting (and more)
     8  *   - Truncation and final polishing by a single insertion sort
     9  *   - Early truncation when no swaps needed in pivoting step
    10  *   - Explicit recursion, guaranteed not to overflow
    11  *   - A few little wrinkles stolen from the GNU |qsort()|.
    12  *   - separate code for non-aligned / aligned / word-size objects
    13  *
    14  * This code may be reproduced freely provided
    15  *   - this file is retained unaltered apart from minor
    16  *     changes for portability and efficiency
    17  *   - no changes are made to this comment
    18  *   - any changes that *are* made are clearly flagged
    19  *   - the _ID string below is altered by inserting, after
    20  *     the date, the string " altered" followed at your option
    21  *     by other material. (Exceptions: you may change the name
    22  *     of the exported routine without changing the ID string.
    23  *     You may change the values of the macros TRUNC_* and
    24  *     PIVOT_THRESHOLD without changing the ID string, provided
    25  *     they remain constants with TRUNC_nonaligned, TRUNC_aligned
    26  *     and TRUNC_words/WORD_BYTES between 8 and 24, and
    27  *     PIVOT_THRESHOLD between 32 and 200.)
    28  *
    29  * You may use it in anything you like; you may make money
    30  * out of it; you may distribute it in object form or as
    31  * part of an executable without including source code;
    32  * you don't have to credit me. (But it would be nice if
    33  * you did.)
    34  *
    35  * If you find problems with this code, or find ways of
    36  * making it significantly faster, please let me know!
    37  * My e-mail address, valid as of early 1998 and certainly
    38  * OK for at least the next 18 months, is
    39  *    gjm11@dpmms.cam.ac.uk
    40  * Thanks!
    41  *
    42  * Gareth McCaughan   Peterhouse   Cambridge   1998
    43  */
    44 #include "SDL_config.h"
    45 
    46 /*
    47 #include <assert.h>
    48 #include <stdlib.h>
    49 #include <string.h>
    50 */
    51 #include "SDL_stdinc.h"
    52 
    53 #define assert(X)
    54 #define malloc	SDL_malloc
    55 #define free	SDL_free
    56 #define memcpy	SDL_memcpy
    57 #define memmove	SDL_memmove
    58 #define qsort	SDL_qsort
    59 
    60 
    61 #ifndef HAVE_QSORT
    62 
    63 static char _ID[] = "<qsort.c gjm 1.12 1998-03-19>";
    64 
    65 /* How many bytes are there per word? (Must be a power of 2,
    66  * and must in fact equal sizeof(int).)
    67  */
    68 #define WORD_BYTES sizeof(int)
    69 
    70 /* How big does our stack need to be? Answer: one entry per
    71  * bit in a |size_t|.
    72  */
    73 #define STACK_SIZE (8*sizeof(size_t))
    74 
    75 /* Different situations have slightly different requirements,
    76  * and we make life epsilon easier by using different truncation
    77  * points for the three different cases.
    78  * So far, I have tuned TRUNC_words and guessed that the same
    79  * value might work well for the other two cases. Of course
    80  * what works well on my machine might work badly on yours.
    81  */
    82 #define TRUNC_nonaligned	12
    83 #define TRUNC_aligned		12
    84 #define TRUNC_words		12*WORD_BYTES   /* nb different meaning */
    85 
    86 /* We use a simple pivoting algorithm for shortish sub-arrays
    87  * and a more complicated one for larger ones. The threshold
    88  * is PIVOT_THRESHOLD.
    89  */
    90 #define PIVOT_THRESHOLD 40
    91 
    92 typedef struct
    93 {
    94     char *first;
    95     char *last;
    96 } stack_entry;
    97 #define pushLeft {stack[stacktop].first=ffirst;stack[stacktop++].last=last;}
    98 #define pushRight {stack[stacktop].first=first;stack[stacktop++].last=llast;}
    99 #define doLeft {first=ffirst;llast=last;continue;}
   100 #define doRight {ffirst=first;last=llast;continue;}
   101 #define pop {if (--stacktop<0) break;\
   102   first=ffirst=stack[stacktop].first;\
   103   last=llast=stack[stacktop].last;\
   104   continue;}
   105 
   106 /* Some comments on the implementation.
   107  * 1. When we finish partitioning the array into "low"
   108  *    and "high", we forget entirely about short subarrays,
   109  *    because they'll be done later by insertion sort.
   110  *    Doing lots of little insertion sorts might be a win
   111  *    on large datasets for locality-of-reference reasons,
   112  *    but it makes the code much nastier and increases
   113  *    bookkeeping overhead.
   114  * 2. We always save the shorter and get to work on the
   115  *    longer. This guarantees that every time we push
   116  *    an item onto the stack its size is <= 1/2 of that
   117  *    of its parent; so the stack can't need more than
   118  *    log_2(max-array-size) entries.
   119  * 3. We choose a pivot by looking at the first, last
   120  *    and middle elements. We arrange them into order
   121  *    because it's easy to do that in conjunction with
   122  *    choosing the pivot, and it makes things a little
   123  *    easier in the partitioning step. Anyway, the pivot
   124  *    is the middle of these three. It's still possible
   125  *    to construct datasets where the algorithm takes
   126  *    time of order n^2, but it simply never happens in
   127  *    practice.
   128  * 3' Newsflash: On further investigation I find that
   129  *    it's easy to construct datasets where median-of-3
   130  *    simply isn't good enough. So on large-ish subarrays
   131  *    we do a more sophisticated pivoting: we take three
   132  *    sets of 3 elements, find their medians, and then
   133  *    take the median of those.
   134  * 4. We copy the pivot element to a separate place
   135  *    because that way we can always do our comparisons
   136  *    directly against a pointer to that separate place,
   137  *    and don't have to wonder "did we move the pivot
   138  *    element?". This makes the inner loop better.
   139  * 5. It's possible to make the pivoting even more
   140  *    reliable by looking at more candidates when n
   141  *    is larger. (Taking this to its logical conclusion
   142  *    results in a variant of quicksort that doesn't
   143  *    have that n^2 worst case.) However, the overhead
   144  *    from the extra bookkeeping means that it's just
   145  *    not worth while.
   146  * 6. This is pretty clean and portable code. Here are
   147  *    all the potential portability pitfalls and problems
   148  *    I know of:
   149  *      - In one place (the insertion sort) I construct
   150  *        a pointer that points just past the end of the
   151  *        supplied array, and assume that (a) it won't
   152  *        compare equal to any pointer within the array,
   153  *        and (b) it will compare equal to a pointer
   154  *        obtained by stepping off the end of the array.
   155  *        These might fail on some segmented architectures.
   156  *      - I assume that there are 8 bits in a |char| when
   157  *        computing the size of stack needed. This would
   158  *        fail on machines with 9-bit or 16-bit bytes.
   159  *      - I assume that if |((int)base&(sizeof(int)-1))==0|
   160  *        and |(size&(sizeof(int)-1))==0| then it's safe to
   161  *        get at array elements via |int*|s, and that if
   162  *        actually |size==sizeof(int)| as well then it's
   163  *        safe to treat the elements as |int|s. This might
   164  *        fail on systems that convert pointers to integers
   165  *        in non-standard ways.
   166  *      - I assume that |8*sizeof(size_t)<=INT_MAX|. This
   167  *        would be false on a machine with 8-bit |char|s,
   168  *        16-bit |int|s and 4096-bit |size_t|s. :-)
   169  */
   170 
   171 /* The recursion logic is the same in each case: */
   172 #define Recurse(Trunc)				\
   173       { size_t l=last-ffirst,r=llast-first;	\
   174         if (l<Trunc) {				\
   175           if (r>=Trunc) doRight			\
   176           else pop				\
   177         }					\
   178         else if (l<=r) { pushLeft; doRight }	\
   179         else if (r>=Trunc) { pushRight; doLeft }\
   180         else doLeft				\
   181       }
   182 
   183 /* and so is the pivoting logic: */
   184 #define Pivot(swapper,sz)			\
   185   if ((size_t)(last-first)>PIVOT_THRESHOLD*sz) mid=pivot_big(first,mid,last,sz,compare);\
   186   else {	\
   187     if (compare(first,mid)<0) {			\
   188       if (compare(mid,last)>0) {		\
   189         swapper(mid,last);			\
   190         if (compare(first,mid)>0) swapper(first,mid);\
   191       }						\
   192     }						\
   193     else {					\
   194       if (compare(mid,last)>0) swapper(first,last)\
   195       else {					\
   196         swapper(first,mid);			\
   197         if (compare(mid,last)>0) swapper(mid,last);\
   198       }						\
   199     }						\
   200     first+=sz; last-=sz;			\
   201   }
   202 
   203 #ifdef DEBUG_QSORT
   204 #include <stdio.h>
   205 #endif
   206 
   207 /* and so is the partitioning logic: */
   208 #define Partition(swapper,sz) {			\
   209   int swapped=0;				\
   210   do {						\
   211     while (compare(first,pivot)<0) first+=sz;	\
   212     while (compare(pivot,last)<0) last-=sz;	\
   213     if (first<last) {				\
   214       swapper(first,last); swapped=1;		\
   215       first+=sz; last-=sz; }			\
   216     else if (first==last) { first+=sz; last-=sz; break; }\
   217   } while (first<=last);			\
   218   if (!swapped) pop				\
   219 }
   220 
   221 /* and so is the pre-insertion-sort operation of putting
   222  * the smallest element into place as a sentinel.
   223  * Doing this makes the inner loop nicer. I got this
   224  * idea from the GNU implementation of qsort().
   225  */
   226 #define PreInsertion(swapper,limit,sz)		\
   227   first=base;					\
   228   last=first + (nmemb>limit ? limit : nmemb-1)*sz;\
   229   while (last!=base) {				\
   230     if (compare(first,last)>0) first=last;	\
   231     last-=sz; }					\
   232   if (first!=base) swapper(first,(char*)base);
   233 
   234 /* and so is the insertion sort, in the first two cases: */
   235 #define Insertion(swapper)			\
   236   last=((char*)base)+nmemb*size;		\
   237   for (first=((char*)base)+size;first!=last;first+=size) {	\
   238     char *test;					\
   239     /* Find the right place for |first|.	\
   240      * My apologies for var reuse. */		\
   241     for (test=first-size;compare(test,first)>0;test-=size) ;	\
   242     test+=size;					\
   243     if (test!=first) {				\
   244       /* Shift everything in [test,first)	\
   245        * up by one, and place |first|		\
   246        * where |test| is. */			\
   247       memcpy(pivot,first,size);			\
   248       memmove(test+size,test,first-test);	\
   249       memcpy(test,pivot,size);			\
   250     }						\
   251   }
   252 
   253 #define SWAP_nonaligned(a,b) { \
   254   register char *aa=(a),*bb=(b); \
   255   register size_t sz=size; \
   256   do { register char t=*aa; *aa++=*bb; *bb++=t; } while (--sz); }
   257 
   258 #define SWAP_aligned(a,b) { \
   259   register int *aa=(int*)(a),*bb=(int*)(b); \
   260   register size_t sz=size; \
   261   do { register int t=*aa;*aa++=*bb; *bb++=t; } while (sz-=WORD_BYTES); }
   262 
   263 #define SWAP_words(a,b) { \
   264   register int t=*((int*)a); *((int*)a)=*((int*)b); *((int*)b)=t; }
   265 
   266 /* ---------------------------------------------------------------------- */
   267 
   268 static char *
   269 pivot_big(char *first, char *mid, char *last, size_t size,
   270           int compare(const void *, const void *))
   271 {
   272     size_t d = (((last - first) / size) >> 3) * size;
   273     char *m1, *m2, *m3;
   274     {
   275         char *a = first, *b = first + d, *c = first + 2 * d;
   276 #ifdef DEBUG_QSORT
   277         fprintf(stderr, "< %d %d %d\n", *(int *) a, *(int *) b, *(int *) c);
   278 #endif
   279         m1 = compare(a, b) < 0 ?
   280             (compare(b, c) < 0 ? b : (compare(a, c) < 0 ? c : a))
   281             : (compare(a, c) < 0 ? a : (compare(b, c) < 0 ? c : b));
   282     }
   283     {
   284         char *a = mid - d, *b = mid, *c = mid + d;
   285 #ifdef DEBUG_QSORT
   286         fprintf(stderr, ". %d %d %d\n", *(int *) a, *(int *) b, *(int *) c);
   287 #endif
   288         m2 = compare(a, b) < 0 ?
   289             (compare(b, c) < 0 ? b : (compare(a, c) < 0 ? c : a))
   290             : (compare(a, c) < 0 ? a : (compare(b, c) < 0 ? c : b));
   291     }
   292     {
   293         char *a = last - 2 * d, *b = last - d, *c = last;
   294 #ifdef DEBUG_QSORT
   295         fprintf(stderr, "> %d %d %d\n", *(int *) a, *(int *) b, *(int *) c);
   296 #endif
   297         m3 = compare(a, b) < 0 ?
   298             (compare(b, c) < 0 ? b : (compare(a, c) < 0 ? c : a))
   299             : (compare(a, c) < 0 ? a : (compare(b, c) < 0 ? c : b));
   300     }
   301 #ifdef DEBUG_QSORT
   302     fprintf(stderr, "-> %d %d %d\n", *(int *) m1, *(int *) m2, *(int *) m3);
   303 #endif
   304     return compare(m1, m2) < 0 ?
   305         (compare(m2, m3) < 0 ? m2 : (compare(m1, m3) < 0 ? m3 : m1))
   306         : (compare(m1, m3) < 0 ? m1 : (compare(m2, m3) < 0 ? m3 : m2));
   307 }
   308 
   309 /* ---------------------------------------------------------------------- */
   310 
   311 static void
   312 qsort_nonaligned(void *base, size_t nmemb, size_t size,
   313                  int (*compare) (const void *, const void *))
   314 {
   315 
   316     stack_entry stack[STACK_SIZE];
   317     int stacktop = 0;
   318     char *first, *last;
   319     char *pivot = malloc(size);
   320     size_t trunc = TRUNC_nonaligned * size;
   321     assert(pivot != 0);
   322 
   323     first = (char *) base;
   324     last = first + (nmemb - 1) * size;
   325 
   326     if ((size_t) (last - first) > trunc) {
   327         char *ffirst = first, *llast = last;
   328         while (1) {
   329             /* Select pivot */
   330             {
   331                 char *mid = first + size * ((last - first) / size >> 1);
   332                 Pivot(SWAP_nonaligned, size);
   333                 memcpy(pivot, mid, size);
   334             }
   335             /* Partition. */
   336             Partition(SWAP_nonaligned, size);
   337             /* Prepare to recurse/iterate. */
   338         Recurse(trunc)}
   339     }
   340     PreInsertion(SWAP_nonaligned, TRUNC_nonaligned, size);
   341     Insertion(SWAP_nonaligned);
   342     free(pivot);
   343 }
   344 
   345 static void
   346 qsort_aligned(void *base, size_t nmemb, size_t size,
   347               int (*compare) (const void *, const void *))
   348 {
   349 
   350     stack_entry stack[STACK_SIZE];
   351     int stacktop = 0;
   352     char *first, *last;
   353     char *pivot = malloc(size);
   354     size_t trunc = TRUNC_aligned * size;
   355     assert(pivot != 0);
   356 
   357     first = (char *) base;
   358     last = first + (nmemb - 1) * size;
   359 
   360     if ((size_t) (last - first) > trunc) {
   361         char *ffirst = first, *llast = last;
   362         while (1) {
   363             /* Select pivot */
   364             {
   365                 char *mid = first + size * ((last - first) / size >> 1);
   366                 Pivot(SWAP_aligned, size);
   367                 memcpy(pivot, mid, size);
   368             }
   369             /* Partition. */
   370             Partition(SWAP_aligned, size);
   371             /* Prepare to recurse/iterate. */
   372         Recurse(trunc)}
   373     }
   374     PreInsertion(SWAP_aligned, TRUNC_aligned, size);
   375     Insertion(SWAP_aligned);
   376     free(pivot);
   377 }
   378 
   379 static void
   380 qsort_words(void *base, size_t nmemb,
   381             int (*compare) (const void *, const void *))
   382 {
   383 
   384     stack_entry stack[STACK_SIZE];
   385     int stacktop = 0;
   386     char *first, *last;
   387     char *pivot = malloc(WORD_BYTES);
   388     assert(pivot != 0);
   389 
   390     first = (char *) base;
   391     last = first + (nmemb - 1) * WORD_BYTES;
   392 
   393     if (last - first > TRUNC_words) {
   394         char *ffirst = first, *llast = last;
   395         while (1) {
   396 #ifdef DEBUG_QSORT
   397             fprintf(stderr, "Doing %d:%d: ",
   398                     (first - (char *) base) / WORD_BYTES,
   399                     (last - (char *) base) / WORD_BYTES);
   400 #endif
   401             /* Select pivot */
   402             {
   403                 char *mid =
   404                     first + WORD_BYTES * ((last - first) / (2 * WORD_BYTES));
   405                 Pivot(SWAP_words, WORD_BYTES);
   406                 *(int *) pivot = *(int *) mid;
   407             }
   408 #ifdef DEBUG_QSORT
   409             fprintf(stderr, "pivot=%d\n", *(int *) pivot);
   410 #endif
   411             /* Partition. */
   412             Partition(SWAP_words, WORD_BYTES);
   413             /* Prepare to recurse/iterate. */
   414         Recurse(TRUNC_words)}
   415     }
   416     PreInsertion(SWAP_words, (TRUNC_words / WORD_BYTES), WORD_BYTES);
   417     /* Now do insertion sort. */
   418     last = ((char *) base) + nmemb * WORD_BYTES;
   419     for (first = ((char *) base) + WORD_BYTES; first != last;
   420          first += WORD_BYTES) {
   421         /* Find the right place for |first|. My apologies for var reuse */
   422         int *pl = (int *) (first - WORD_BYTES), *pr = (int *) first;
   423         *(int *) pivot = *(int *) first;
   424         for (; compare(pl, pivot) > 0; pr = pl, --pl) {
   425             *pr = *pl;
   426         }
   427         if (pr != (int *) first)
   428             *pr = *(int *) pivot;
   429     }
   430     free(pivot);
   431 }
   432 
   433 /* ---------------------------------------------------------------------- */
   434 
   435 void
   436 qsort(void *base, size_t nmemb, size_t size,
   437       int (*compare) (const void *, const void *))
   438 {
   439 
   440     if (nmemb <= 1)
   441         return;
   442     if (((uintptr_t) base | size) & (WORD_BYTES - 1))
   443         qsort_nonaligned(base, nmemb, size, compare);
   444     else if (size != WORD_BYTES)
   445         qsort_aligned(base, nmemb, size, compare);
   446     else
   447         qsort_words(base, nmemb, compare);
   448 }
   449 
   450 #endif /* !HAVE_QSORT */
   451 /* vi: set ts=4 sw=4 expandtab: */