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