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