root/source3/lib/ldb/common/qsort.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. ldb_qsort

   1 /* Copyright (C) 1991,1992,1996,1997,1999,2004 Free Software Foundation, Inc.
   2    This file is part of the GNU C Library.
   3    Written by Douglas C. Schmidt (schmidt@ics.uci.edu).
   4 
   5    The GNU C Library is free software; you can redistribute it and/or
   6    modify it under the terms of the GNU Lesser General Public
   7    License as published by the Free Software Foundation; either
   8    version 2.1 of the License, or (at your option) any later version.
   9 
  10    The GNU C Library is distributed in the hope that it will be useful,
  11    but WITHOUT ANY WARRANTY; without even the implied warranty of
  12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  13    Lesser General Public License for more details.
  14 
  15    You should have received a copy of the GNU Lesser General Public
  16    License along with the GNU C Library; if not, see <http://www.gnu.org/licenses/>. */
  17 
  18 /* If you consider tuning this algorithm, you should consult first:
  19    Engineering a sort function; Jon Bentley and M. Douglas McIlroy;
  20    Software - Practice and Experience; Vol. 23 (11), 1249-1265, 1993.  */
  21 
  22 /* Modified to be used in samba4 by
  23  * Simo Sorce <idra@samba.org>          2005
  24  */
  25 
  26 #include "includes.h"
  27 #include "ldb/include/includes.h"
  28 
  29 /* Byte-wise swap two items of size SIZE. */
  30 #define SWAP(a, b, size)                                                      \
  31   do                                                                          \
  32     {                                                                         \
  33       register size_t __size = (size);                                        \
  34       register char *__a = (a), *__b = (b);                                   \
  35       do                                                                      \
  36         {                                                                     \
  37           char __tmp = *__a;                                                  \
  38           *__a++ = *__b;                                                      \
  39           *__b++ = __tmp;                                                     \
  40         } while (--__size > 0);                                               \
  41     } while (0)
  42 
  43 /* Discontinue quicksort algorithm when partition gets below this size.
  44    This particular magic number was chosen to work best on a Sun 4/260. */
  45 #define MAX_THRESH 4
  46 
  47 /* Stack node declarations used to store unfulfilled partition obligations. */
  48 typedef struct
  49   {
  50     char *lo;
  51     char *hi;
  52   } stack_node;
  53 
  54 /* The next 4 #defines implement a very fast in-line stack abstraction. */
  55 /* The stack needs log (total_elements) entries (we could even subtract
  56    log(MAX_THRESH)).  Since total_elements has type size_t, we get as
  57    upper bound for log (total_elements):
  58    bits per byte (CHAR_BIT) * sizeof(size_t).  */
  59 #ifndef CHAR_BIT
  60 #define CHAR_BIT 8
  61 #endif
  62 #define STACK_SIZE      (CHAR_BIT * sizeof(size_t))
  63 #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
  64 #define POP(low, high)  ((void) (--top, (low = top->lo), (high = top->hi)))
  65 #define STACK_NOT_EMPTY (stack < top)
  66 
  67 
  68 /* Order size using quicksort.  This implementation incorporates
  69    four optimizations discussed in Sedgewick:
  70 
  71    1. Non-recursive, using an explicit stack of pointer that store the
  72       next array partition to sort.  To save time, this maximum amount
  73       of space required to store an array of SIZE_MAX is allocated on the
  74       stack.  Assuming a 32-bit (64 bit) integer for size_t, this needs
  75       only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
  76       Pretty cheap, actually.
  77 
  78    2. Chose the pivot element using a median-of-three decision tree.
  79       This reduces the probability of selecting a bad pivot value and
  80       eliminates certain extraneous comparisons.
  81 
  82    3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
  83       insertion sort to order the MAX_THRESH items within each partition.
  84       This is a big win, since insertion sort is faster for small, mostly
  85       sorted array segments.
  86 
  87    4. The larger of the two sub-partitions is always pushed onto the
  88       stack first, with the algorithm then concentrating on the
  89       smaller partition.  This *guarantees* no more than log (total_elems)
  90       stack size is needed (actually O(1) in this case)!  */
  91 
  92 void ldb_qsort (void *const pbase, size_t total_elems, size_t size,
     /* [<][>][^][v][top][bottom][index][help] */
  93                 void *opaque, ldb_qsort_cmp_fn_t cmp)
  94 {
  95   register char *base_ptr = (char *) pbase;
  96 
  97   const size_t max_thresh = MAX_THRESH * size;
  98 
  99   if (total_elems == 0)
 100     /* Avoid lossage with unsigned arithmetic below.  */
 101     return;
 102 
 103   if (total_elems > MAX_THRESH)
 104     {
 105       char *lo = base_ptr;
 106       char *hi = &lo[size * (total_elems - 1)];
 107       stack_node stack[STACK_SIZE];
 108       stack_node *top = stack;
 109 
 110       PUSH (NULL, NULL);
 111 
 112       while (STACK_NOT_EMPTY)
 113         {
 114           char *left_ptr;
 115           char *right_ptr;
 116 
 117           /* Select median value from among LO, MID, and HI. Rearrange
 118              LO and HI so the three values are sorted. This lowers the
 119              probability of picking a pathological pivot value and
 120              skips a comparison for both the LEFT_PTR and RIGHT_PTR in
 121              the while loops. */
 122 
 123           char *mid = lo + size * ((hi - lo) / size >> 1);
 124 
 125           if ((*cmp) ((void *) mid, (void *) lo, opaque) < 0)
 126             SWAP (mid, lo, size);
 127           if ((*cmp) ((void *) hi, (void *) mid, opaque) < 0)
 128             SWAP (mid, hi, size);
 129           else
 130             goto jump_over;
 131           if ((*cmp) ((void *) mid, (void *) lo, opaque) < 0)
 132             SWAP (mid, lo, size);
 133         jump_over:;
 134 
 135           left_ptr  = lo + size;
 136           right_ptr = hi - size;
 137 
 138           /* Here's the famous ``collapse the walls'' section of quicksort.
 139              Gotta like those tight inner loops!  They are the main reason
 140              that this algorithm runs much faster than others. */
 141           do
 142             {
 143               while ((*cmp) ((void *) left_ptr, (void *) mid, opaque) < 0)
 144                 left_ptr += size;
 145 
 146               while ((*cmp) ((void *) mid, (void *) right_ptr, opaque) < 0)
 147                 right_ptr -= size;
 148 
 149               if (left_ptr < right_ptr)
 150                 {
 151                   SWAP (left_ptr, right_ptr, size);
 152                   if (mid == left_ptr)
 153                     mid = right_ptr;
 154                   else if (mid == right_ptr)
 155                     mid = left_ptr;
 156                   left_ptr += size;
 157                   right_ptr -= size;
 158                 }
 159               else if (left_ptr == right_ptr)
 160                 {
 161                   left_ptr += size;
 162                   right_ptr -= size;
 163                   break;
 164                 }
 165             }
 166           while (left_ptr <= right_ptr);
 167 
 168           /* Set up pointers for next iteration.  First determine whether
 169              left and right partitions are below the threshold size.  If so,
 170              ignore one or both.  Otherwise, push the larger partition's
 171              bounds on the stack and continue sorting the smaller one. */
 172 
 173           if ((size_t) (right_ptr - lo) <= max_thresh)
 174             {
 175               if ((size_t) (hi - left_ptr) <= max_thresh)
 176                 /* Ignore both small partitions. */
 177                 POP (lo, hi);
 178               else
 179                 /* Ignore small left partition. */
 180                 lo = left_ptr;
 181             }
 182           else if ((size_t) (hi - left_ptr) <= max_thresh)
 183             /* Ignore small right partition. */
 184             hi = right_ptr;
 185           else if ((right_ptr - lo) > (hi - left_ptr))
 186             {
 187               /* Push larger left partition indices. */
 188               PUSH (lo, right_ptr);
 189               lo = left_ptr;
 190             }
 191           else
 192             {
 193               /* Push larger right partition indices. */
 194               PUSH (left_ptr, hi);
 195               hi = right_ptr;
 196             }
 197         }
 198     }
 199 
 200   /* Once the BASE_PTR array is partially sorted by quicksort the rest
 201      is completely sorted using insertion sort, since this is efficient
 202      for partitions below MAX_THRESH size. BASE_PTR points to the beginning
 203      of the array to sort, and END_PTR points at the very last element in
 204      the array (*not* one beyond it!). */
 205 
 206 #define min(x, y) ((x) < (y) ? (x) : (y))
 207 
 208   {
 209     char *const end_ptr = &base_ptr[size * (total_elems - 1)];
 210     char *tmp_ptr = base_ptr;
 211     char *thresh = min(end_ptr, base_ptr + max_thresh);
 212     register char *run_ptr;
 213 
 214     /* Find smallest element in first threshold and place it at the
 215        array's beginning.  This is the smallest array element,
 216        and the operation speeds up insertion sort's inner loop. */
 217 
 218     for (run_ptr = tmp_ptr + size; run_ptr <= thresh; run_ptr += size)
 219       if ((*cmp) ((void *) run_ptr, (void *) tmp_ptr, opaque) < 0)
 220         tmp_ptr = run_ptr;
 221 
 222     if (tmp_ptr != base_ptr)
 223       SWAP (tmp_ptr, base_ptr, size);
 224 
 225     /* Insertion sort, running from left-hand-side up to right-hand-side.  */
 226 
 227     run_ptr = base_ptr + size;
 228     while ((run_ptr += size) <= end_ptr)
 229       {
 230         tmp_ptr = run_ptr - size;
 231         while ((*cmp) ((void *) run_ptr, (void *) tmp_ptr, opaque) < 0)
 232           tmp_ptr -= size;
 233 
 234         tmp_ptr += size;
 235         if (tmp_ptr != run_ptr)
 236           {
 237             char *trav;
 238 
 239             trav = run_ptr + size;
 240             while (--trav >= run_ptr)
 241               {
 242                 char c = *trav;
 243                 char *hi, *lo;
 244 
 245                 for (hi = lo = trav; (lo -= size) >= tmp_ptr; hi = lo)
 246                   *hi = *lo;
 247                 *hi = c;
 248               }
 249           }
 250       }
 251   }
 252 }

/* [<][>][^][v][top][bottom][index][help] */