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