src/stdlib/SDL_qsort.c
changeset 1330 450721ad5436
child 1331 1cbaeee565b1
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/src/stdlib/SDL_qsort.c	Mon Feb 06 08:28:51 2006 +0000
     1.3 @@ -0,0 +1,418 @@
     1.4 +/* qsort.c
     1.5 + * (c) 1998 Gareth McCaughan
     1.6 + *
     1.7 + * This is a drop-in replacement for the C library's |qsort()| routine.
     1.8 + *
     1.9 + * Features:
    1.10 + *   - Median-of-three pivoting (and more)
    1.11 + *   - Truncation and final polishing by a single insertion sort
    1.12 + *   - Early truncation when no swaps needed in pivoting step
    1.13 + *   - Explicit recursion, guaranteed not to overflow
    1.14 + *   - A few little wrinkles stolen from the GNU |qsort()|.
    1.15 + *   - separate code for non-aligned / aligned / word-size objects
    1.16 + *
    1.17 + * This code may be reproduced freely provided
    1.18 + *   - this file is retained unaltered apart from minor
    1.19 + *     changes for portability and efficiency
    1.20 + *   - no changes are made to this comment
    1.21 + *   - any changes that *are* made are clearly flagged
    1.22 + *   - the _ID string below is altered by inserting, after
    1.23 + *     the date, the string " altered" followed at your option
    1.24 + *     by other material. (Exceptions: you may change the name
    1.25 + *     of the exported routine without changing the ID string.
    1.26 + *     You may change the values of the macros TRUNC_* and
    1.27 + *     PIVOT_THRESHOLD without changing the ID string, provided
    1.28 + *     they remain constants with TRUNC_nonaligned, TRUNC_aligned
    1.29 + *     and TRUNC_words/WORD_BYTES between 8 and 24, and
    1.30 + *     PIVOT_THRESHOLD between 32 and 200.)
    1.31 + *
    1.32 + * You may use it in anything you like; you may make money
    1.33 + * out of it; you may distribute it in object form or as
    1.34 + * part of an executable without including source code;
    1.35 + * you don't have to credit me. (But it would be nice if
    1.36 + * you did.)
    1.37 + *
    1.38 + * If you find problems with this code, or find ways of
    1.39 + * making it significantly faster, please let me know!
    1.40 + * My e-mail address, valid as of early 1998 and certainly
    1.41 + * OK for at least the next 18 months, is
    1.42 + *    gjm11@dpmms.cam.ac.uk
    1.43 + * Thanks!
    1.44 + *
    1.45 + * Gareth McCaughan   Peterhouse   Cambridge   1998
    1.46 + */
    1.47 +
    1.48 +/*
    1.49 +#include <assert.h>
    1.50 +#include <stdlib.h>
    1.51 +#include <string.h>
    1.52 +*/
    1.53 +#define assert(X)
    1.54 +#include "SDL_stdlib.h"
    1.55 +#include "SDL_string.h"
    1.56 +
    1.57 +#ifndef HAVE_QSORT
    1.58 +
    1.59 +static char _ID[]="<qsort.c gjm 1.12 1998-03-19>";
    1.60 +
    1.61 +/* How many bytes are there per word? (Must be a power of 2,
    1.62 + * and must in fact equal sizeof(int).)
    1.63 + */
    1.64 +#define WORD_BYTES sizeof(int)
    1.65 +
    1.66 +/* How big does our stack need to be? Answer: one entry per
    1.67 + * bit in a |size_t|.
    1.68 + */
    1.69 +#define STACK_SIZE (8*sizeof(size_t))
    1.70 +
    1.71 +/* Different situations have slightly different requirements,
    1.72 + * and we make life epsilon easier by using different truncation
    1.73 + * points for the three different cases.
    1.74 + * So far, I have tuned TRUNC_words and guessed that the same
    1.75 + * value might work well for the other two cases. Of course
    1.76 + * what works well on my machine might work badly on yours.
    1.77 + */
    1.78 +#define TRUNC_nonaligned	12
    1.79 +#define TRUNC_aligned		12
    1.80 +#define TRUNC_words		12*WORD_BYTES	/* nb different meaning */
    1.81 +
    1.82 +/* We use a simple pivoting algorithm for shortish sub-arrays
    1.83 + * and a more complicated one for larger ones. The threshold
    1.84 + * is PIVOT_THRESHOLD.
    1.85 + */
    1.86 +#define PIVOT_THRESHOLD 40
    1.87 +
    1.88 +typedef struct { char * first; char * last; } stack_entry;
    1.89 +#define pushLeft {stack[stacktop].first=ffirst;stack[stacktop++].last=last;}
    1.90 +#define pushRight {stack[stacktop].first=first;stack[stacktop++].last=llast;}
    1.91 +#define doLeft {first=ffirst;llast=last;continue;}
    1.92 +#define doRight {ffirst=first;last=llast;continue;}
    1.93 +#define pop {if (--stacktop<0) break;\
    1.94 +  first=ffirst=stack[stacktop].first;\
    1.95 +  last=llast=stack[stacktop].last;\
    1.96 +  continue;}
    1.97 +
    1.98 +/* Some comments on the implementation.
    1.99 + * 1. When we finish partitioning the array into "low"
   1.100 + *    and "high", we forget entirely about short subarrays,
   1.101 + *    because they'll be done later by insertion sort.
   1.102 + *    Doing lots of little insertion sorts might be a win
   1.103 + *    on large datasets for locality-of-reference reasons,
   1.104 + *    but it makes the code much nastier and increases
   1.105 + *    bookkeeping overhead.
   1.106 + * 2. We always save the shorter and get to work on the
   1.107 + *    longer. This guarantees that every time we push
   1.108 + *    an item onto the stack its size is <= 1/2 of that
   1.109 + *    of its parent; so the stack can't need more than
   1.110 + *    log_2(max-array-size) entries.
   1.111 + * 3. We choose a pivot by looking at the first, last
   1.112 + *    and middle elements. We arrange them into order
   1.113 + *    because it's easy to do that in conjunction with
   1.114 + *    choosing the pivot, and it makes things a little
   1.115 + *    easier in the partitioning step. Anyway, the pivot
   1.116 + *    is the middle of these three. It's still possible
   1.117 + *    to construct datasets where the algorithm takes
   1.118 + *    time of order n^2, but it simply never happens in
   1.119 + *    practice.
   1.120 + * 3' Newsflash: On further investigation I find that
   1.121 + *    it's easy to construct datasets where median-of-3
   1.122 + *    simply isn't good enough. So on large-ish subarrays
   1.123 + *    we do a more sophisticated pivoting: we take three
   1.124 + *    sets of 3 elements, find their medians, and then
   1.125 + *    take the median of those.
   1.126 + * 4. We copy the pivot element to a separate place
   1.127 + *    because that way we can always do our comparisons
   1.128 + *    directly against a pointer to that separate place,
   1.129 + *    and don't have to wonder "did we move the pivot
   1.130 + *    element?". This makes the inner loop better.
   1.131 + * 5. It's possible to make the pivoting even more
   1.132 + *    reliable by looking at more candidates when n
   1.133 + *    is larger. (Taking this to its logical conclusion
   1.134 + *    results in a variant of quicksort that doesn't
   1.135 + *    have that n^2 worst case.) However, the overhead
   1.136 + *    from the extra bookkeeping means that it's just
   1.137 + *    not worth while.
   1.138 + * 6. This is pretty clean and portable code. Here are
   1.139 + *    all the potential portability pitfalls and problems
   1.140 + *    I know of:
   1.141 + *      - In one place (the insertion sort) I construct
   1.142 + *        a pointer that points just past the end of the
   1.143 + *        supplied array, and assume that (a) it won't
   1.144 + *        compare equal to any pointer within the array,
   1.145 + *        and (b) it will compare equal to a pointer
   1.146 + *        obtained by stepping off the end of the array.
   1.147 + *        These might fail on some segmented architectures.
   1.148 + *      - I assume that there are 8 bits in a |char| when
   1.149 + *        computing the size of stack needed. This would
   1.150 + *        fail on machines with 9-bit or 16-bit bytes.
   1.151 + *      - I assume that if |((int)base&(sizeof(int)-1))==0|
   1.152 + *        and |(size&(sizeof(int)-1))==0| then it's safe to
   1.153 + *        get at array elements via |int*|s, and that if
   1.154 + *        actually |size==sizeof(int)| as well then it's
   1.155 + *        safe to treat the elements as |int|s. This might
   1.156 + *        fail on systems that convert pointers to integers
   1.157 + *        in non-standard ways.
   1.158 + *      - I assume that |8*sizeof(size_t)<=INT_MAX|. This
   1.159 + *        would be false on a machine with 8-bit |char|s,
   1.160 + *        16-bit |int|s and 4096-bit |size_t|s. :-)
   1.161 + */
   1.162 +
   1.163 +/* The recursion logic is the same in each case: */
   1.164 +#define Recurse(Trunc)				\
   1.165 +      { size_t l=last-ffirst,r=llast-first;	\
   1.166 +        if (l<Trunc) {				\
   1.167 +          if (r>=Trunc) doRight			\
   1.168 +          else pop				\
   1.169 +        }					\
   1.170 +        else if (l<=r) { pushLeft; doRight }	\
   1.171 +        else if (r>=Trunc) { pushRight; doLeft }\
   1.172 +        else doLeft				\
   1.173 +      }
   1.174 +
   1.175 +/* and so is the pivoting logic: */
   1.176 +#define Pivot(swapper,sz)			\
   1.177 +  if ((size_t)(last-first)>PIVOT_THRESHOLD*sz) mid=pivot_big(first,mid,last,sz,compare);\
   1.178 +  else {	\
   1.179 +    if (compare(first,mid)<0) {			\
   1.180 +      if (compare(mid,last)>0) {		\
   1.181 +        swapper(mid,last);			\
   1.182 +        if (compare(first,mid)>0) swapper(first,mid);\
   1.183 +      }						\
   1.184 +    }						\
   1.185 +    else {					\
   1.186 +      if (compare(mid,last)>0) swapper(first,last)\
   1.187 +      else {					\
   1.188 +        swapper(first,mid);			\
   1.189 +        if (compare(mid,last)>0) swapper(mid,last);\
   1.190 +      }						\
   1.191 +    }						\
   1.192 +    first+=sz; last-=sz;			\
   1.193 +  }
   1.194 +
   1.195 +#ifdef DEBUG_QSORT
   1.196 +#include <stdio.h>
   1.197 +#endif
   1.198 +
   1.199 +/* and so is the partitioning logic: */
   1.200 +#define Partition(swapper,sz) {			\
   1.201 +  int swapped=0;				\
   1.202 +  do {						\
   1.203 +    while (compare(first,pivot)<0) first+=sz;	\
   1.204 +    while (compare(pivot,last)<0) last-=sz;	\
   1.205 +    if (first<last) {				\
   1.206 +      swapper(first,last); swapped=1;		\
   1.207 +      first+=sz; last-=sz; }			\
   1.208 +    else if (first==last) { first+=sz; last-=sz; break; }\
   1.209 +  } while (first<=last);			\
   1.210 +  if (!swapped) pop				\
   1.211 +}
   1.212 +
   1.213 +/* and so is the pre-insertion-sort operation of putting
   1.214 + * the smallest element into place as a sentinel.
   1.215 + * Doing this makes the inner loop nicer. I got this
   1.216 + * idea from the GNU implementation of qsort().
   1.217 + */
   1.218 +#define PreInsertion(swapper,limit,sz)		\
   1.219 +  first=base;					\
   1.220 +  last=first + (nmemb>limit ? limit : nmemb-1)*sz;\
   1.221 +  while (last!=base) {				\
   1.222 +    if (compare(first,last)>0) first=last;	\
   1.223 +    last-=sz; }					\
   1.224 +  if (first!=base) swapper(first,(char*)base);
   1.225 +
   1.226 +/* and so is the insertion sort, in the first two cases: */
   1.227 +#define Insertion(swapper)			\
   1.228 +  last=((char*)base)+nmemb*size;		\
   1.229 +  for (first=((char*)base)+size;first!=last;first+=size) {	\
   1.230 +    char *test;					\
   1.231 +    /* Find the right place for |first|.	\
   1.232 +     * My apologies for var reuse. */		\
   1.233 +    for (test=first-size;compare(test,first)>0;test-=size) ;	\
   1.234 +    test+=size;					\
   1.235 +    if (test!=first) {				\
   1.236 +      /* Shift everything in [test,first)	\
   1.237 +       * up by one, and place |first|		\
   1.238 +       * where |test| is. */			\
   1.239 +      memcpy(pivot,first,size);			\
   1.240 +      memmove(test+size,test,first-test);	\
   1.241 +      memcpy(test,pivot,size);			\
   1.242 +    }						\
   1.243 +  }
   1.244 +
   1.245 +#define SWAP_nonaligned(a,b) { \
   1.246 +  register char *aa=(a),*bb=(b); \
   1.247 +  register size_t sz=size; \
   1.248 +  do { register char t=*aa; *aa++=*bb; *bb++=t; } while (--sz); }
   1.249 +
   1.250 +#define SWAP_aligned(a,b) { \
   1.251 +  register int *aa=(int*)(a),*bb=(int*)(b); \
   1.252 +  register size_t sz=size; \
   1.253 +  do { register int t=*aa;*aa++=*bb; *bb++=t; } while (sz-=WORD_BYTES); }
   1.254 +
   1.255 +#define SWAP_words(a,b) { \
   1.256 +  register int t=*((int*)a); *((int*)a)=*((int*)b); *((int*)b)=t; }
   1.257 +
   1.258 +/* ---------------------------------------------------------------------- */
   1.259 +
   1.260 +static char * pivot_big(char *first, char *mid, char *last, size_t size,
   1.261 +                        int compare(const void *, const void *)) {
   1.262 +  int d=(((last-first)/size)>>3)*size;
   1.263 +  char *m1,*m2,*m3;
   1.264 +  { char *a=first, *b=first+d, *c=first+2*d;
   1.265 +#ifdef DEBUG_QSORT
   1.266 +fprintf(stderr,"< %d %d %d\n",*(int*)a,*(int*)b,*(int*)c);
   1.267 +#endif
   1.268 +    m1 = compare(a,b)<0 ?
   1.269 +           (compare(b,c)<0 ? b : (compare(a,c)<0 ? c : a))
   1.270 +         : (compare(a,c)<0 ? a : (compare(b,c)<0 ? c : b));
   1.271 +  }
   1.272 +  { char *a=mid-d, *b=mid, *c=mid+d;
   1.273 +#ifdef DEBUG_QSORT
   1.274 +fprintf(stderr,". %d %d %d\n",*(int*)a,*(int*)b,*(int*)c);
   1.275 +#endif
   1.276 +    m2 = compare(a,b)<0 ?
   1.277 +           (compare(b,c)<0 ? b : (compare(a,c)<0 ? c : a))
   1.278 +         : (compare(a,c)<0 ? a : (compare(b,c)<0 ? c : b));
   1.279 +  }
   1.280 +  { char *a=last-2*d, *b=last-d, *c=last;
   1.281 +#ifdef DEBUG_QSORT
   1.282 +fprintf(stderr,"> %d %d %d\n",*(int*)a,*(int*)b,*(int*)c);
   1.283 +#endif
   1.284 +    m3 = compare(a,b)<0 ?
   1.285 +           (compare(b,c)<0 ? b : (compare(a,c)<0 ? c : a))
   1.286 +         : (compare(a,c)<0 ? a : (compare(b,c)<0 ? c : b));
   1.287 +  }
   1.288 +#ifdef DEBUG_QSORT
   1.289 +fprintf(stderr,"-> %d %d %d\n",*(int*)m1,*(int*)m2,*(int*)m3);
   1.290 +#endif
   1.291 +  return compare(m1,m2)<0 ?
   1.292 +           (compare(m2,m3)<0 ? m2 : (compare(m1,m3)<0 ? m3 : m1))
   1.293 +         : (compare(m1,m3)<0 ? m1 : (compare(m2,m3)<0 ? m3 : m2));
   1.294 +}
   1.295 +
   1.296 +/* ---------------------------------------------------------------------- */
   1.297 +
   1.298 +static void qsort_nonaligned(void *base, size_t nmemb, size_t size,
   1.299 +           int (*compare)(const void *, const void *)) {
   1.300 +
   1.301 +  stack_entry stack[STACK_SIZE];
   1.302 +  int stacktop=0;
   1.303 +  char *first,*last;
   1.304 +  char *pivot=malloc(size);
   1.305 +  size_t trunc=TRUNC_nonaligned*size;
   1.306 +  assert(pivot!=0);
   1.307 +
   1.308 +  first=(char*)base; last=first+(nmemb-1)*size;
   1.309 +
   1.310 +  if ((size_t)(last-first)>trunc) {
   1.311 +    char *ffirst=first, *llast=last;
   1.312 +    while (1) {
   1.313 +      /* Select pivot */
   1.314 +      { char * mid=first+size*((last-first)/size >> 1);
   1.315 +        Pivot(SWAP_nonaligned,size);
   1.316 +        memcpy(pivot,mid,size);
   1.317 +      }
   1.318 +      /* Partition. */
   1.319 +      Partition(SWAP_nonaligned,size);
   1.320 +      /* Prepare to recurse/iterate. */
   1.321 +      Recurse(trunc)
   1.322 +    }
   1.323 +  }
   1.324 +  PreInsertion(SWAP_nonaligned,TRUNC_nonaligned,size);
   1.325 +  Insertion(SWAP_nonaligned);
   1.326 +  free(pivot);
   1.327 +}
   1.328 +
   1.329 +static void qsort_aligned(void *base, size_t nmemb, size_t size,
   1.330 +           int (*compare)(const void *, const void *)) {
   1.331 +
   1.332 +  stack_entry stack[STACK_SIZE];
   1.333 +  int stacktop=0;
   1.334 +  char *first,*last;
   1.335 +  char *pivot=malloc(size);
   1.336 +  size_t trunc=TRUNC_aligned*size;
   1.337 +  assert(pivot!=0);
   1.338 +
   1.339 +  first=(char*)base; last=first+(nmemb-1)*size;
   1.340 +
   1.341 +  if ((size_t)(last-first)>trunc) {
   1.342 +    char *ffirst=first,*llast=last;
   1.343 +    while (1) {
   1.344 +      /* Select pivot */
   1.345 +      { char * mid=first+size*((last-first)/size >> 1);
   1.346 +        Pivot(SWAP_aligned,size);
   1.347 +        memcpy(pivot,mid,size);
   1.348 +      }
   1.349 +      /* Partition. */
   1.350 +      Partition(SWAP_aligned,size);
   1.351 +      /* Prepare to recurse/iterate. */
   1.352 +      Recurse(trunc)
   1.353 +    }
   1.354 +  }
   1.355 +  PreInsertion(SWAP_aligned,TRUNC_aligned,size);
   1.356 +  Insertion(SWAP_aligned);
   1.357 +  free(pivot);
   1.358 +}
   1.359 +
   1.360 +static void qsort_words(void *base, size_t nmemb,
   1.361 +           int (*compare)(const void *, const void *)) {
   1.362 +
   1.363 +  stack_entry stack[STACK_SIZE];
   1.364 +  int stacktop=0;
   1.365 +  char *first,*last;
   1.366 +  char *pivot=malloc(WORD_BYTES);
   1.367 +  assert(pivot!=0);
   1.368 +
   1.369 +  first=(char*)base; last=first+(nmemb-1)*WORD_BYTES;
   1.370 +
   1.371 +  if (last-first>TRUNC_words) {
   1.372 +    char *ffirst=first, *llast=last;
   1.373 +    while (1) {
   1.374 +#ifdef DEBUG_QSORT
   1.375 +fprintf(stderr,"Doing %d:%d: ",
   1.376 +        (first-(char*)base)/WORD_BYTES,
   1.377 +        (last-(char*)base)/WORD_BYTES);
   1.378 +#endif
   1.379 +      /* Select pivot */
   1.380 +      { char * mid=first+WORD_BYTES*((last-first) / (2*WORD_BYTES));
   1.381 +        Pivot(SWAP_words,WORD_BYTES);
   1.382 +        *(int*)pivot=*(int*)mid;
   1.383 +      }
   1.384 +#ifdef DEBUG_QSORT
   1.385 +fprintf(stderr,"pivot=%d\n",*(int*)pivot);
   1.386 +#endif
   1.387 +      /* Partition. */
   1.388 +      Partition(SWAP_words,WORD_BYTES);
   1.389 +      /* Prepare to recurse/iterate. */
   1.390 +      Recurse(TRUNC_words)
   1.391 +    }
   1.392 +  }
   1.393 +  PreInsertion(SWAP_words,(TRUNC_words/WORD_BYTES),WORD_BYTES);
   1.394 +  /* Now do insertion sort. */
   1.395 +  last=((char*)base)+nmemb*WORD_BYTES;
   1.396 +  for (first=((char*)base)+WORD_BYTES;first!=last;first+=WORD_BYTES) {
   1.397 +    /* Find the right place for |first|. My apologies for var reuse */
   1.398 +    int *pl=(int*)(first-WORD_BYTES),*pr=(int*)first;
   1.399 +    *(int*)pivot=*(int*)first;
   1.400 +    for (;compare(pl,pivot)>0;pr=pl,--pl) {
   1.401 +      *pr=*pl; }
   1.402 +    if (pr!=(int*)first) *pr=*(int*)pivot;
   1.403 +  }
   1.404 +  free(pivot);
   1.405 +}
   1.406 +
   1.407 +/* ---------------------------------------------------------------------- */
   1.408 +
   1.409 +void SDL_qsort(void *base, size_t nmemb, size_t size,
   1.410 +           int (*compare)(const void *, const void *)) {
   1.411 +
   1.412 +  if (nmemb<=1) return;
   1.413 +  if (((int)base|size)&(WORD_BYTES-1))
   1.414 +    qsort_nonaligned(base,nmemb,size,compare);
   1.415 +  else if (size!=WORD_BYTES)
   1.416 +    qsort_aligned(base,nmemb,size,compare);
   1.417 +  else
   1.418 +    qsort_words(base,nmemb,compare);
   1.419 +}
   1.420 +
   1.421 +#endif /* !HAVE_QSORT */
   1.422 \ No newline at end of file