src/stdlib/SDL_qsort.c
author Ryan C. Gordon <icculus@icculus.org>
Mon, 05 Jan 2015 01:41:42 -0500
changeset 9306 817656bd36ec
parent 8093 b43765095a6f
child 10068 19998f9082dc
permissions -rw-r--r--
Clang static analysis builds should use C runtime directly.

This is a little macro magic to use malloc() directly instead of SDL_malloc(),
etc, so static analysis tests that know about the C runtime can function
properly, and understand that we are dealing with heap allocations, etc.

This changed our static analysis report from 5 outstanding bugs to 30.

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