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