src/stdlib/SDL_qsort.c
changeset 10068 19998f9082dc
parent 9306 817656bd36ec
child 10069 ba33b870b45c
equal deleted inserted replaced
10067:5be0ebfaad70 10068:19998f9082dc
     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 #if defined(__clang_analyzer__) && !defined(SDL_DISABLE_ANALYZE_MACROS)
       
    46 #define SDL_DISABLE_ANALYZE_MACROS 1
       
    47 #endif
       
    48 
       
    49 #include "../SDL_internal.h"
     1 #include "../SDL_internal.h"
    50 
     2 
    51 /*
       
    52 #include <assert.h>
       
    53 #include <stdlib.h>
       
    54 #include <string.h>
       
    55 */
       
    56 #include "SDL_stdinc.h"
     3 #include "SDL_stdinc.h"
    57 #include "SDL_assert.h"
     4 #include "SDL_assert.h"
    58 
     5 
    59 #if defined(HAVE_QSORT)
     6 #if defined(HAVE_QSORT)
    60 void
     7 void
    62 {
     9 {
    63     qsort(base, nmemb, size, compare);
    10     qsort(base, nmemb, size, compare);
    64 }
    11 }
    65 #else
    12 #else
    66 
    13 
    67 #ifdef assert
    14 #ifdef REGTEST
    68 #undef assert
    15 #undef REGTEST
    69 #endif
    16 #endif
    70 #define assert(X) SDL_assert(X)
    17 
    71 #ifdef malloc
    18 #ifdef TEST
    72 #undef malloc
    19 #undef TEST
    73 #endif
    20 #endif
    74 #define malloc	SDL_malloc
    21 
    75 #ifdef free
    22 #ifndef _PDCLIB_memswp
    76 #undef free
    23 #define _PDCLIB_memswp( i, j, size ) char tmp; do { tmp = *i; *i++ = *j; *j++ = tmp; } while ( --size );
    77 #endif
    24 #endif
    78 #define free	SDL_free
    25 
    79 #ifdef memcpy
    26 #ifndef _PDCLIB_size_t
    80 #undef memcpy
    27 #define _PDCLIB_size_t size_t
    81 #endif
    28 #endif
    82 #define memcpy	SDL_memcpy
    29 
    83 #ifdef memmove
    30 #define qsort SDL_qsort
    84 #undef memmove
    31 
    85 #endif
    32 #define inline SDL_INLINE
    86 #define memmove	SDL_memmove
    33 
    87 #ifdef qsort
    34 /*
    88 #undef qsort
    35 This code came from PDCLib, under the public domain. Specifically this:
    89 #endif
    36 https://bitbucket.org/pdclib/pdclib/raw/a82b02d0c7d4ed633b97f2a7639d9a10b1c92ec8/functions/stdlib/qsort.c
    90 #define qsort	SDL_qsort
    37 The _PDCLIB_memswp macro was from
    91 
    38 https://bitbucket.org/pdclib/pdclib/src/a82b02d0c7d4ed633b97f2a7639d9a10b1c92ec8/platform/posix/internals/_PDCLIB_config.h?at=default&fileviewer=file-view-default#_PDCLIB_config.h-28
    92 static const char _ID[] = "<qsort.c gjm 1.12 1998-03-19>";
    39 
    93 
    40 Everything below this comment until the HAVE_QSORT #endif was from PDCLib.
    94 /* How many bytes are there per word? (Must be a power of 2,
    41 --ryan.
    95  * and must in fact equal sizeof(int).)
    42 */
    96  */
    43 
    97 #define WORD_BYTES sizeof(int)
    44 /* $Id$ */
    98 
    45 
    99 /* How big does our stack need to be? Answer: one entry per
    46 /* qsort( void *, size_t, size_t, int(*)( const void *, const void * ) )
   100  * bit in a |size_t|.
    47 
   101  */
    48    This file is part of the Public Domain C Library (PDCLib).
   102 #define STACK_SIZE (8*sizeof(size_t))
    49    Permission is granted to use, modify, and / or redistribute at will.
   103 
    50 */
   104 /* Different situations have slightly different requirements,
    51 
   105  * and we make life epsilon easier by using different truncation
    52 #include <stdlib.h>
   106  * points for the three different cases.
    53 
   107  * So far, I have tuned TRUNC_words and guessed that the same
    54 #ifndef REGTEST
   108  * value might work well for the other two cases. Of course
    55 
   109  * what works well on my machine might work badly on yours.
    56 /* This implementation is taken from Paul Edward's PDPCLIB.
   110  */
    57 
   111 #define TRUNC_nonaligned	12
    58    Original code is credited to Raymond Gardner, Englewood CO.
   112 #define TRUNC_aligned		12
    59    Minor mods are credited to Paul Edwards.
   113 #define TRUNC_words		12*WORD_BYTES   /* nb different meaning */
    60    Some reformatting and simplification done by Martin Baute.
   114 
    61    All code is still Public Domain.
   115 /* We use a simple pivoting algorithm for shortish sub-arrays
    62 */
   116  * and a more complicated one for larger ones. The threshold
    63 
   117  * is PIVOT_THRESHOLD.
    64 /* Wrapper for _PDCLIB_memswp protects against multiple argument evaluation. */
   118  */
    65 static inline void memswp( char * i, char * j, size_t size )
   119 #define PIVOT_THRESHOLD 40
    66 {
   120 
    67     _PDCLIB_memswp( i, j, size );
   121 typedef struct
    68 }
   122 {
    69 
   123     char *first;
    70 /* For small sets, insertion sort is faster than quicksort.
   124     char *last;
    71    T is the threshold below which insertion sort will be used.
   125 } stack_entry;
    72    Must be 3 or larger.
   126 #define pushLeft {stack[stacktop].first=ffirst;stack[stacktop++].last=last;}
    73 */
   127 #define pushRight {stack[stacktop].first=first;stack[stacktop++].last=llast;}
    74 #define T 7
   128 #define doLeft {first=ffirst;llast=last;continue;}
    75 
   129 #define doRight {ffirst=first;last=llast;continue;}
    76 /* Macros for handling the QSort stack */
   130 #define pop {if (--stacktop<0) break;\
    77 #define PREPARE_STACK char * stack[STACKSIZE]; char * * stackptr = stack
   131   first=ffirst=stack[stacktop].first;\
    78 #define PUSH( base, limit ) stackptr[0] = base; stackptr[1] = limit; stackptr += 2
   132   last=llast=stack[stacktop].last;\
    79 #define POP( base, limit ) stackptr -= 2; base = stackptr[0]; limit = stackptr[1]
   133   continue;}
    80 /* TODO: Stack usage is log2( nmemb ) (minus what T shaves off the worst case).
   134 
    81          Worst-case nmemb is platform dependent and should probably be 
   135 /* Some comments on the implementation.
    82          configured through _PDCLIB_config.h.
   136  * 1. When we finish partitioning the array into "low"
    83 */
   137  *    and "high", we forget entirely about short subarrays,
    84 #define STACKSIZE 64
   138  *    because they'll be done later by insertion sort.
    85 
   139  *    Doing lots of little insertion sorts might be a win
    86 void qsort( void * base, size_t nmemb, size_t size, int (*compar)( const void *, const void * ) )
   140  *    on large datasets for locality-of-reference reasons,
    87 {
   141  *    but it makes the code much nastier and increases
    88     char * i;
   142  *    bookkeeping overhead.
    89     char * j;
   143  * 2. We always save the shorter and get to work on the
    90     _PDCLIB_size_t thresh = T * size;
   144  *    longer. This guarantees that every time we push
    91     char * base_          = (char *)base;
   145  *    an item onto the stack its size is <= 1/2 of that
    92     char * limit          = base_ + nmemb * size;
   146  *    of its parent; so the stack can't need more than
    93     PREPARE_STACK;
   147  *    log_2(max-array-size) entries.
    94 
   148  * 3. We choose a pivot by looking at the first, last
    95     for ( ;; )
   149  *    and middle elements. We arrange them into order
       
   150  *    because it's easy to do that in conjunction with
       
   151  *    choosing the pivot, and it makes things a little
       
   152  *    easier in the partitioning step. Anyway, the pivot
       
   153  *    is the middle of these three. It's still possible
       
   154  *    to construct datasets where the algorithm takes
       
   155  *    time of order n^2, but it simply never happens in
       
   156  *    practice.
       
   157  * 3' Newsflash: On further investigation I find that
       
   158  *    it's easy to construct datasets where median-of-3
       
   159  *    simply isn't good enough. So on large-ish subarrays
       
   160  *    we do a more sophisticated pivoting: we take three
       
   161  *    sets of 3 elements, find their medians, and then
       
   162  *    take the median of those.
       
   163  * 4. We copy the pivot element to a separate place
       
   164  *    because that way we can always do our comparisons
       
   165  *    directly against a pointer to that separate place,
       
   166  *    and don't have to wonder "did we move the pivot
       
   167  *    element?". This makes the inner loop better.
       
   168  * 5. It's possible to make the pivoting even more
       
   169  *    reliable by looking at more candidates when n
       
   170  *    is larger. (Taking this to its logical conclusion
       
   171  *    results in a variant of quicksort that doesn't
       
   172  *    have that n^2 worst case.) However, the overhead
       
   173  *    from the extra bookkeeping means that it's just
       
   174  *    not worth while.
       
   175  * 6. This is pretty clean and portable code. Here are
       
   176  *    all the potential portability pitfalls and problems
       
   177  *    I know of:
       
   178  *      - In one place (the insertion sort) I construct
       
   179  *        a pointer that points just past the end of the
       
   180  *        supplied array, and assume that (a) it won't
       
   181  *        compare equal to any pointer within the array,
       
   182  *        and (b) it will compare equal to a pointer
       
   183  *        obtained by stepping off the end of the array.
       
   184  *        These might fail on some segmented architectures.
       
   185  *      - I assume that there are 8 bits in a |char| when
       
   186  *        computing the size of stack needed. This would
       
   187  *        fail on machines with 9-bit or 16-bit bytes.
       
   188  *      - I assume that if |((int)base&(sizeof(int)-1))==0|
       
   189  *        and |(size&(sizeof(int)-1))==0| then it's safe to
       
   190  *        get at array elements via |int*|s, and that if
       
   191  *        actually |size==sizeof(int)| as well then it's
       
   192  *        safe to treat the elements as |int|s. This might
       
   193  *        fail on systems that convert pointers to integers
       
   194  *        in non-standard ways.
       
   195  *      - I assume that |8*sizeof(size_t)<=INT_MAX|. This
       
   196  *        would be false on a machine with 8-bit |char|s,
       
   197  *        16-bit |int|s and 4096-bit |size_t|s. :-)
       
   198  */
       
   199 
       
   200 /* The recursion logic is the same in each case: */
       
   201 #define Recurse(Trunc)				\
       
   202       { size_t l=last-ffirst,r=llast-first;	\
       
   203         if (l<Trunc) {				\
       
   204           if (r>=Trunc) doRight			\
       
   205           else pop				\
       
   206         }					\
       
   207         else if (l<=r) { pushLeft; doRight }	\
       
   208         else if (r>=Trunc) { pushRight; doLeft }\
       
   209         else doLeft				\
       
   210       }
       
   211 
       
   212 /* and so is the pivoting logic: */
       
   213 #define Pivot(swapper,sz)			\
       
   214   if ((size_t)(last-first)>PIVOT_THRESHOLD*sz) mid=pivot_big(first,mid,last,sz,compare);\
       
   215   else {	\
       
   216     if (compare(first,mid)<0) {			\
       
   217       if (compare(mid,last)>0) {		\
       
   218         swapper(mid,last);			\
       
   219         if (compare(first,mid)>0) swapper(first,mid);\
       
   220       }						\
       
   221     }						\
       
   222     else {					\
       
   223       if (compare(mid,last)>0) swapper(first,last)\
       
   224       else {					\
       
   225         swapper(first,mid);			\
       
   226         if (compare(mid,last)>0) swapper(mid,last);\
       
   227       }						\
       
   228     }						\
       
   229     first+=sz; last-=sz;			\
       
   230   }
       
   231 
       
   232 #ifdef DEBUG_QSORT
       
   233 #include <stdio.h>
       
   234 #endif
       
   235 
       
   236 /* and so is the partitioning logic: */
       
   237 #define Partition(swapper,sz) {			\
       
   238   int swapped=0;				\
       
   239   do {						\
       
   240     while (compare(first,pivot)<0) first+=sz;	\
       
   241     while (compare(pivot,last)<0) last-=sz;	\
       
   242     if (first<last) {				\
       
   243       swapper(first,last); swapped=1;		\
       
   244       first+=sz; last-=sz; }			\
       
   245     else if (first==last) { first+=sz; last-=sz; break; }\
       
   246   } while (first<=last);			\
       
   247   if (!swapped) pop				\
       
   248 }
       
   249 
       
   250 /* and so is the pre-insertion-sort operation of putting
       
   251  * the smallest element into place as a sentinel.
       
   252  * Doing this makes the inner loop nicer. I got this
       
   253  * idea from the GNU implementation of qsort().
       
   254  */
       
   255 #define PreInsertion(swapper,limit,sz)		\
       
   256   first=base;					\
       
   257   last=first + (nmemb>limit ? limit : nmemb-1)*sz;\
       
   258   while (last!=base) {				\
       
   259     if (compare(first,last)>0) first=last;	\
       
   260     last-=sz; }					\
       
   261   if (first!=base) swapper(first,(char*)base);
       
   262 
       
   263 /* and so is the insertion sort, in the first two cases: */
       
   264 #define Insertion(swapper)			\
       
   265   last=((char*)base)+nmemb*size;		\
       
   266   for (first=((char*)base)+size;first!=last;first+=size) {	\
       
   267     char *test;					\
       
   268     /* Find the right place for |first|.	\
       
   269      * My apologies for var reuse. */		\
       
   270     for (test=first-size;compare(test,first)>0;test-=size) ;	\
       
   271     test+=size;					\
       
   272     if (test!=first) {				\
       
   273       /* Shift everything in [test,first)	\
       
   274        * up by one, and place |first|		\
       
   275        * where |test| is. */			\
       
   276       memcpy(pivot,first,size);			\
       
   277       memmove(test+size,test,first-test);	\
       
   278       memcpy(test,pivot,size);			\
       
   279     }						\
       
   280   }
       
   281 
       
   282 #define SWAP_nonaligned(a,b) { \
       
   283   register char *aa=(a),*bb=(b); \
       
   284   register size_t sz=size; \
       
   285   do { register char t=*aa; *aa++=*bb; *bb++=t; } while (--sz); }
       
   286 
       
   287 #define SWAP_aligned(a,b) { \
       
   288   register int *aa=(int*)(a),*bb=(int*)(b); \
       
   289   register size_t sz=size; \
       
   290   do { register int t=*aa;*aa++=*bb; *bb++=t; } while (sz-=WORD_BYTES); }
       
   291 
       
   292 #define SWAP_words(a,b) { \
       
   293   register int t=*((int*)a); *((int*)a)=*((int*)b); *((int*)b)=t; }
       
   294 
       
   295 /* ---------------------------------------------------------------------- */
       
   296 
       
   297 static char *
       
   298 pivot_big(char *first, char *mid, char *last, size_t size,
       
   299           int compare(const void *, const void *))
       
   300 {
       
   301     size_t d = (((last - first) / size) >> 3) * size;
       
   302     char *m1, *m2, *m3;
       
   303     {
    96     {
   304         char *a = first, *b = first + d, *c = first + 2 * d;
    97         if ( (size_t)( limit - base_ ) > thresh ) /* QSort for more than T elements. */
   305 #ifdef DEBUG_QSORT
    98         {
   306         fprintf(stderr, "< %d %d %d\n", *(int *) a, *(int *) b, *(int *) c);
    99             /* We work from second to last - first will be pivot element. */
   307 #endif
   100             i = base_ + size;
   308         m1 = compare(a, b) < 0 ?
   101             j = limit - size;
   309             (compare(b, c) < 0 ? b : (compare(a, c) < 0 ? c : a))
   102             /* We swap first with middle element, then sort that with second
   310             : (compare(a, c) < 0 ? a : (compare(b, c) < 0 ? c : b));
   103                and last element so that eventually first element is the median
       
   104                of the three - avoiding pathological pivots.
       
   105                TODO: Instead of middle element, chose one randomly.
       
   106             */
       
   107             memswp( ( ( ( (size_t)( limit - base_ ) ) / size ) / 2 ) * size + base_, base_, size );
       
   108             if ( compar( i, j ) > 0 ) memswp( i, j, size );
       
   109             if ( compar( base_, j ) > 0 ) memswp( base_, j, size );
       
   110             if ( compar( i, base_ ) > 0 ) memswp( i, base_, size );
       
   111             /* Now we have the median for pivot element, entering main Quicksort. */
       
   112             for ( ;; )
       
   113             {
       
   114                 do
       
   115                 {
       
   116                     /* move i right until *i >= pivot */
       
   117                     i += size;
       
   118                 } while ( compar( i, base_ ) < 0 );
       
   119                 do
       
   120                 {
       
   121                     /* move j left until *j <= pivot */
       
   122                     j -= size;
       
   123                 } while ( compar( j, base_ ) > 0 );
       
   124                 if ( i > j )
       
   125                 {
       
   126                     /* break loop if pointers crossed */
       
   127                     break;
       
   128                 }
       
   129                 /* else swap elements, keep scanning */
       
   130                 memswp( i, j, size );
       
   131             }
       
   132             /* move pivot into correct place */
       
   133             memswp( base_, j, size );
       
   134             /* larger subfile base / limit to stack, sort smaller */
       
   135             if ( j - base_ > limit - i )
       
   136             {
       
   137                 /* left is larger */
       
   138                 PUSH( base_, j );
       
   139                 base_ = i;
       
   140             }
       
   141             else
       
   142             {
       
   143                 /* right is larger */
       
   144                 PUSH( i, limit );
       
   145                 limit = j;
       
   146             }
       
   147         }
       
   148         else /* insertion sort for less than T elements              */
       
   149         {
       
   150             for ( j = base_, i = j + size; i < limit; j = i, i += size )
       
   151             {
       
   152                 for ( ; compar( j, j + size ) > 0; j -= size )
       
   153                 {
       
   154                     memswp( j, j + size, size );
       
   155                     if ( j == base_ )
       
   156                     {
       
   157                         break;
       
   158                     }
       
   159                 }
       
   160             }
       
   161             if ( stackptr != stack )           /* if any entries on stack  */
       
   162             {
       
   163                 POP( base_, limit );
       
   164             }
       
   165             else                       /* else stack empty, done   */
       
   166             {
       
   167                 break;
       
   168             }
       
   169         }
   311     }
   170     }
   312     {
   171 }
   313         char *a = mid - d, *b = mid, *c = mid + d;
   172 
   314 #ifdef DEBUG_QSORT
   173 #endif
   315         fprintf(stderr, ". %d %d %d\n", *(int *) a, *(int *) b, *(int *) c);
   174 
   316 #endif
   175 #ifdef TEST
   317         m2 = compare(a, b) < 0 ?
   176 #include <_PDCLIB_test.h>
   318             (compare(b, c) < 0 ? b : (compare(a, c) < 0 ? c : a))
   177 #include <string.h>
   319             : (compare(a, c) < 0 ? a : (compare(b, c) < 0 ? c : b));
   178 #include <limits.h>
   320     }
   179 
   321     {
   180 static int compare( const void * left, const void * right )
   322         char *a = last - 2 * d, *b = last - d, *c = last;
   181 {
   323 #ifdef DEBUG_QSORT
   182     return *( (unsigned char *)left ) - *( (unsigned char *)right );
   324         fprintf(stderr, "> %d %d %d\n", *(int *) a, *(int *) b, *(int *) c);
   183 }
   325 #endif
   184 
   326         m3 = compare(a, b) < 0 ?
   185 int main( void )
   327             (compare(b, c) < 0 ? b : (compare(a, c) < 0 ? c : a))
   186 {
   328             : (compare(a, c) < 0 ? a : (compare(b, c) < 0 ? c : b));
   187     char presort[] = { "shreicnyjqpvozxmbt" };
   329     }
   188     char sorted1[] = { "bcehijmnopqrstvxyz" };
   330 #ifdef DEBUG_QSORT
   189     char sorted2[] = { "bticjqnyozpvreshxm" };
   331     fprintf(stderr, "-> %d %d %d\n", *(int *) m1, *(int *) m2, *(int *) m3);
   190     char s[19];
   332 #endif
   191     strcpy( s, presort );
   333     return compare(m1, m2) < 0 ?
   192     qsort( s, 18, 1, compare );
   334         (compare(m2, m3) < 0 ? m2 : (compare(m1, m3) < 0 ? m3 : m1))
   193     TESTCASE( strcmp( s, sorted1 ) == 0 );
   335         : (compare(m1, m3) < 0 ? m1 : (compare(m2, m3) < 0 ? m3 : m2));
   194     strcpy( s, presort );
   336 }
   195     qsort( s, 9, 2, compare );
   337 
   196     TESTCASE( strcmp( s, sorted2 ) == 0 );
   338 /* ---------------------------------------------------------------------- */
   197     strcpy( s, presort );
   339 
   198     qsort( s, 1, 1, compare );
   340 static void
   199     TESTCASE( strcmp( s, presort ) == 0 );
   341 qsort_nonaligned(void *base, size_t nmemb, size_t size,
   200 #if defined(REGTEST) && (__BSD_VISIBLE || __APPLE__)
   342                  int (*compare) (const void *, const void *))
   201     puts( "qsort.c: Skipping test #4 for BSD as it goes into endless loop here." );
   343 {
   202 #else
   344 
   203     qsort( s, 100, 0, compare );
   345     stack_entry stack[STACK_SIZE];
   204     TESTCASE( strcmp( s, presort ) == 0 );
   346     int stacktop = 0;
   205 #endif
   347     char *first, *last;
   206     return TEST_RESULTS;
   348     char *pivot = malloc(size);
   207 }
   349     size_t trunc = TRUNC_nonaligned * size;
   208 
   350     assert(pivot != 0);
   209 #endif
   351 
   210 
   352     first = (char *) base;
   211 #endif /* HAVE_QSORT */
   353     last = first + (nmemb - 1) * size;
       
   354 
       
   355     if ((size_t) (last - first) > trunc) {
       
   356         char *ffirst = first, *llast = last;
       
   357         while (1) {
       
   358             /* Select pivot */
       
   359             {
       
   360                 char *mid = first + size * ((last - first) / size >> 1);
       
   361                 Pivot(SWAP_nonaligned, size);
       
   362                 memcpy(pivot, mid, size);
       
   363             }
       
   364             /* Partition. */
       
   365             Partition(SWAP_nonaligned, size);
       
   366             /* Prepare to recurse/iterate. */
       
   367         Recurse(trunc)}
       
   368     }
       
   369     PreInsertion(SWAP_nonaligned, TRUNC_nonaligned, size);
       
   370     Insertion(SWAP_nonaligned);
       
   371     free(pivot);
       
   372 }
       
   373 
       
   374 static void
       
   375 qsort_aligned(void *base, size_t nmemb, size_t size,
       
   376               int (*compare) (const void *, const void *))
       
   377 {
       
   378 
       
   379     stack_entry stack[STACK_SIZE];
       
   380     int stacktop = 0;
       
   381     char *first, *last;
       
   382     char *pivot = malloc(size);
       
   383     size_t trunc = TRUNC_aligned * size;
       
   384     assert(pivot != 0);
       
   385 
       
   386     first = (char *) base;
       
   387     last = first + (nmemb - 1) * size;
       
   388 
       
   389     if ((size_t) (last - first) > trunc) {
       
   390         char *ffirst = first, *llast = last;
       
   391         while (1) {
       
   392             /* Select pivot */
       
   393             {
       
   394                 char *mid = first + size * ((last - first) / size >> 1);
       
   395                 Pivot(SWAP_aligned, size);
       
   396                 memcpy(pivot, mid, size);
       
   397             }
       
   398             /* Partition. */
       
   399             Partition(SWAP_aligned, size);
       
   400             /* Prepare to recurse/iterate. */
       
   401         Recurse(trunc)}
       
   402     }
       
   403     PreInsertion(SWAP_aligned, TRUNC_aligned, size);
       
   404     Insertion(SWAP_aligned);
       
   405     free(pivot);
       
   406 }
       
   407 
       
   408 static void
       
   409 qsort_words(void *base, size_t nmemb,
       
   410             int (*compare) (const void *, const void *))
       
   411 {
       
   412 
       
   413     stack_entry stack[STACK_SIZE];
       
   414     int stacktop = 0;
       
   415     char *first, *last;
       
   416     char *pivot = malloc(WORD_BYTES);
       
   417     assert(pivot != 0);
       
   418 
       
   419     first = (char *) base;
       
   420     last = first + (nmemb - 1) * WORD_BYTES;
       
   421 
       
   422     if (last - first > TRUNC_words) {
       
   423         char *ffirst = first, *llast = last;
       
   424         while (1) {
       
   425 #ifdef DEBUG_QSORT
       
   426             fprintf(stderr, "Doing %d:%d: ",
       
   427                     (first - (char *) base) / WORD_BYTES,
       
   428                     (last - (char *) base) / WORD_BYTES);
       
   429 #endif
       
   430             /* Select pivot */
       
   431             {
       
   432                 char *mid =
       
   433                     first + WORD_BYTES * ((last - first) / (2 * WORD_BYTES));
       
   434                 Pivot(SWAP_words, WORD_BYTES);
       
   435                 *(int *) pivot = *(int *) mid;
       
   436             }
       
   437 #ifdef DEBUG_QSORT
       
   438             fprintf(stderr, "pivot=%d\n", *(int *) pivot);
       
   439 #endif
       
   440             /* Partition. */
       
   441             Partition(SWAP_words, WORD_BYTES);
       
   442             /* Prepare to recurse/iterate. */
       
   443         Recurse(TRUNC_words)}
       
   444     }
       
   445     PreInsertion(SWAP_words, (TRUNC_words / WORD_BYTES), WORD_BYTES);
       
   446     /* Now do insertion sort. */
       
   447     last = ((char *) base) + nmemb * WORD_BYTES;
       
   448     for (first = ((char *) base) + WORD_BYTES; first != last;
       
   449          first += WORD_BYTES) {
       
   450         /* Find the right place for |first|. My apologies for var reuse */
       
   451         int *pl = (int *) (first - WORD_BYTES), *pr = (int *) first;
       
   452         *(int *) pivot = *(int *) first;
       
   453         for (; compare(pl, pivot) > 0; pr = pl, --pl) {
       
   454             *pr = *pl;
       
   455         }
       
   456         if (pr != (int *) first)
       
   457             *pr = *(int *) pivot;
       
   458     }
       
   459     free(pivot);
       
   460 }
       
   461 
       
   462 /* ---------------------------------------------------------------------- */
       
   463 
       
   464 void
       
   465 qsort(void *base, size_t nmemb, size_t size,
       
   466       int (*compare) (const void *, const void *))
       
   467 {
       
   468 
       
   469     if (nmemb <= 1)
       
   470         return;
       
   471     if (((uintptr_t) base | size) & (WORD_BYTES - 1))
       
   472         qsort_nonaligned(base, nmemb, size, compare);
       
   473     else if (size != WORD_BYTES)
       
   474         qsort_aligned(base, nmemb, size, compare);
       
   475     else
       
   476         qsort_words(base, nmemb, compare);
       
   477 }
       
   478 
       
   479 #endif /* !SDL_qsort */
       
   480 
   212 
   481 /* vi: set ts=4 sw=4 expandtab: */
   213 /* vi: set ts=4 sw=4 expandtab: */