Advertisement
Guest User

Untitled

a guest
Sep 4th, 2010
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 11.38 KB | None | 0 0
  1. /* $Id: qsort.h,v 1.5 2008-01-28 18:16:49 mjt Exp $
  2.  * Adopted from GNU glibc by Mjt.
  3.  * See stdlib/qsort.c in glibc */
  4.  
  5. /* Copyright (C) 1991, 1992, 1996, 1997, 1999 Free Software Foundation, Inc.
  6.    This file is part of the GNU C Library.
  7.    Written by Douglas C. Schmidt (schmidt@ics.uci.edu).
  8.  
  9.    The GNU C Library is free software; you can redistribute it and/or
  10.    modify it under the terms of the GNU Lesser General Public
  11.    License as published by the Free Software Foundation; either
  12.    version 2.1 of the License, or (at your option) any later version.
  13.  
  14.    The GNU C Library is distributed in the hope that it will be useful,
  15.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  16.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  17.    Lesser General Public License for more details.
  18.  
  19.    You should have received a copy of the GNU Lesser General Public
  20.    License along with the GNU C Library; if not, write to the Free
  21.    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  22.    02111-1307 USA.  */
  23.  
  24. /* in-line qsort implementation.  Differs from traditional qsort() routine
  25.  * in that it is a macro, not a function, and instead of passing an address
  26.  * of a comparison routine to the function, it is possible to inline
  27.  * comparison routine, thus speeding up sorting a lot.
  28.  *
  29.  * Usage:
  30.  *  #include "iqsort.h"
  31.  *  #define islt(a,b) (strcmp((*a),(*b))<0)
  32.  *  char *arr[];
  33.  *  int n;
  34.  *  QSORT(char*, arr, n, islt);
  35.  *
  36.  * The "prototype" and 4 arguments are:
  37.  *  QSORT(TYPE,BASE,NELT,ISLT)
  38.  *  1) type of each element, TYPE,
  39.  *  2) address of the beginning of the array, of type TYPE*,
  40.  *  3) number of elements in the array, and
  41.  *  4) comparision routine.
  42.  * Array pointer and number of elements are referenced only once.
  43.  * This is similar to a call
  44.  *  qsort(BASE,NELT,sizeof(TYPE),ISLT)
  45.  * with the difference in last parameter.
  46.  * Note the islt macro/routine (it receives pointers to two elements):
  47.  * the only condition of interest is whenever one element is less than
  48.  * another, no other conditions (greather than, equal to etc) are tested.
  49.  * So, for example, to define integer sort, use:
  50.  *  #define islt(a,b) ((*a)<(*b))
  51.  *  QSORT(int, arr, n, islt)
  52.  *
  53.  * The macro could be used to implement a sorting function (see examples
  54.  * below), or to implement the sorting algorithm inline.  That is, either
  55.  * create a sorting function and use it whenever you want to sort something,
  56.  * or use QSORT() macro directly instead a call to such routine.  Note that
  57.  * the macro expands to quite some code (compiled size of int qsort on x86
  58.  * is about 700..800 bytes).
  59.  *
  60.  * Using this macro directly it isn't possible to implement traditional
  61.  * qsort() routine, because the macro assumes sizeof(element) == sizeof(TYPE),
  62.  * while qsort() allows element size to be different.
  63.  *
  64.  * Several ready-to-use examples:
  65.  *
  66.  * Sorting array of integers:
  67.  * void int_qsort(int *arr, unsigned n) {
  68.  * #define int_lt(a,b) ((*a)<(*b))
  69.  *   QSORT(int, arr, n, int_lt);
  70.  * }
  71.  *
  72.  * Sorting array of string pointers:
  73.  * void str_qsort(char *arr[], unsigned n) {
  74.  * #define str_lt(a,b) (strcmp((*a),(*b)) < 0)
  75.  *   QSORT(char*, arr, n, str_lt);
  76.  * }
  77.  *
  78.  * Sorting array of structures:
  79.  *
  80.  * struct elt {
  81.  *   int key;
  82.  *   ...
  83.  * };
  84.  * void elt_qsort(struct elt *arr, unsigned n) {
  85.  * #define elt_lt(a,b) ((a)->key < (b)->key)
  86.  *  QSORT(struct elt, arr, n, elt_lt);
  87.  * }
  88.  *
  89.  * And so on.
  90.  */
  91.  
  92. /* Swap two items pointed to by A and B using temporary buffer t. */
  93. #define _QSORT_SWAP(a, b, t) ((void)((t = *a), (*a = *b), (*b = t)))
  94.  
  95. /* Discontinue quicksort algorithm when partition gets below this size.
  96.    This particular magic number was chosen to work best on a Sun 4/260. */
  97. #define _QSORT_MAX_THRESH 4
  98.  
  99. /* Stack node declarations used to store unfulfilled partition obligations
  100.  * (inlined in QSORT).
  101. typedef struct {
  102.   QSORT_TYPE *_lo, *_hi;
  103. } qsort_stack_node;
  104.  */
  105.  
  106. /* The next 4 #defines implement a very fast in-line stack abstraction. */
  107. /* The stack needs log (total_elements) entries (we could even subtract
  108.    log(MAX_THRESH)).  Since total_elements has type unsigned, we get as
  109.    upper bound for log (total_elements):
  110.    bits per byte (CHAR_BIT) * sizeof(unsigned).  */
  111. #define _QSORT_STACK_SIZE   (8 * sizeof(unsigned))
  112. #define _QSORT_PUSH(top, low, high) \
  113.     (((top->_lo = (low)), (top->_hi = (high)), ++top))
  114. #define _QSORT_POP(low, high, top)  \
  115.     ((--top, (low = top->_lo), (high = top->_hi)))
  116. #define _QSORT_STACK_NOT_EMPTY  (_stack < _top)
  117.  
  118.  
  119. /* Order size using quicksort.  This implementation incorporates
  120.    four optimizations discussed in Sedgewick:
  121.  
  122.    1. Non-recursive, using an explicit stack of pointer that store the
  123.       next array partition to sort.  To save time, this maximum amount
  124.       of space required to store an array of SIZE_MAX is allocated on the
  125.       stack.  Assuming a 32-bit (64 bit) integer for size_t, this needs
  126.       only 32 * sizeof(stack_node) == 256 bytes (for 64 bit: 1024 bytes).
  127.       Pretty cheap, actually.
  128.  
  129.    2. Chose the pivot element using a median-of-three decision tree.
  130.       This reduces the probability of selecting a bad pivot value and
  131.       eliminates certain extraneous comparisons.
  132.  
  133.    3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
  134.       insertion sort to order the MAX_THRESH items within each partition.
  135.       This is a big win, since insertion sort is faster for small, mostly
  136.       sorted array segments.
  137.  
  138.    4. The larger of the two sub-partitions is always pushed onto the
  139.       stack first, with the algorithm then concentrating on the
  140.       smaller partition.  This *guarantees* no more than log (total_elems)
  141.       stack size is needed (actually O(1) in this case)!  */
  142.  
  143. /* The main code starts here... */
  144. #define QSORT(QSORT_TYPE,QSORT_BASE,QSORT_NELT,QSORT_LT)        \
  145. {                                   \
  146.   QSORT_TYPE *const _base = (QSORT_BASE);               \
  147.   const unsigned _elems = (QSORT_NELT);                 \
  148.   QSORT_TYPE _hold;                         \
  149.                                     \
  150.   /* Don't declare two variables of type QSORT_TYPE in a single     \
  151.    * statement: eg `TYPE a, b;', in case if TYPE is a pointer,      \
  152.    * expands to `type* a, b;' wich isn't what we want.          \
  153.    */                                   \
  154.                                     \
  155.   if (_elems > _QSORT_MAX_THRESH) {                 \
  156.     QSORT_TYPE *_lo = _base;                        \
  157.     QSORT_TYPE *_hi = _lo + _elems - 1;                 \
  158.     struct {                                \
  159.       QSORT_TYPE *_hi; QSORT_TYPE *_lo;                 \
  160.     } _stack[_QSORT_STACK_SIZE], *_top = _stack + 1;            \
  161.                                     \
  162.     while (_QSORT_STACK_NOT_EMPTY) {                    \
  163.       QSORT_TYPE *_left_ptr; QSORT_TYPE *_right_ptr;            \
  164.                                     \
  165.       /* Select median value from among LO, MID, and HI. Rearrange  \
  166.          LO and HI so the three values are sorted. This lowers the  \
  167.          probability of picking a pathological pivot value and      \
  168.          skips a comparison for both the LEFT_PTR and RIGHT_PTR in  \
  169.          the while loops. */                        \
  170.                                     \
  171.       QSORT_TYPE *_mid = _lo + ((_hi - _lo) >> 1);          \
  172.                                     \
  173.       if (QSORT_LT (_mid, _lo))                     \
  174.         _QSORT_SWAP (_mid, _lo, _hold);                 \
  175.       if (QSORT_LT (_hi, _mid)) {                   \
  176.         _QSORT_SWAP (_mid, _hi, _hold);                 \
  177.         if (QSORT_LT (_mid, _lo))                   \
  178.           _QSORT_SWAP (_mid, _lo, _hold);               \
  179.       }                                 \
  180.                                     \
  181.       _left_ptr  = _lo + 1;                     \
  182.       _right_ptr = _hi - 1;                     \
  183.                                     \
  184.       /* Here's the famous ``collapse the walls'' section of quicksort. \
  185.          Gotta like those tight inner loops!  They are the main reason  \
  186.          that this algorithm runs much faster than others. */       \
  187.       do {                              \
  188.         while (QSORT_LT (_left_ptr, _mid))              \
  189.          ++_left_ptr;                           \
  190.                                     \
  191.         while (QSORT_LT (_mid, _right_ptr))             \
  192.           --_right_ptr;                         \
  193.                                     \
  194.         if (_left_ptr < _right_ptr) {                   \
  195.           _QSORT_SWAP (_left_ptr, _right_ptr, _hold);           \
  196.           if (_mid == _left_ptr)                    \
  197.             _mid = _right_ptr;                      \
  198.           else if (_mid == _right_ptr)                  \
  199.             _mid = _left_ptr;                       \
  200.           ++_left_ptr;                          \
  201.           --_right_ptr;                         \
  202.         }                               \
  203.         else if (_left_ptr == _right_ptr) {             \
  204.           ++_left_ptr;                          \
  205.           --_right_ptr;                         \
  206.           break;                            \
  207.         }                               \
  208.       } while (_left_ptr <= _right_ptr);                \
  209.                                     \
  210.      /* Set up pointers for next iteration.  First determine whether    \
  211.         left and right partitions are below the threshold size.  If so, \
  212.         ignore one or both.  Otherwise, push the larger partition's \
  213.         bounds on the stack and continue sorting the smaller one. */    \
  214.                                     \
  215.       if (_right_ptr - _lo <= _QSORT_MAX_THRESH) {          \
  216.         if (_hi - _left_ptr <= _QSORT_MAX_THRESH)           \
  217.           /* Ignore both small partitions. */               \
  218.           _QSORT_POP (_lo, _hi, _top);                  \
  219.         else                                \
  220.           /* Ignore small left partition. */                \
  221.           _lo = _left_ptr;                      \
  222.       }                                 \
  223.       else if (_hi - _left_ptr <= _QSORT_MAX_THRESH)            \
  224.         /* Ignore small right partition. */             \
  225.         _hi = _right_ptr;                       \
  226.       else if (_right_ptr - _lo > _hi - _left_ptr) {            \
  227.         /* Push larger left partition indices. */           \
  228.         _QSORT_PUSH (_top, _lo, _right_ptr);                \
  229.         _lo = _left_ptr;                        \
  230.       }                                 \
  231.       else {                                \
  232.         /* Push larger right partition indices. */          \
  233.         _QSORT_PUSH (_top, _left_ptr, _hi);             \
  234.         _hi = _right_ptr;                       \
  235.       }                                 \
  236.     }                                   \
  237.   }                                 \
  238.                                     \
  239.   /* Once the BASE array is partially sorted by quicksort the rest  \
  240.      is completely sorted using insertion sort, since this is efficient \
  241.      for partitions below MAX_THRESH size. BASE points to the       \
  242.      beginning of the array to sort, and END_PTR points at the very \
  243.      last element in the array (*not* one beyond it!). */       \
  244.                                     \
  245.   {                                 \
  246.     QSORT_TYPE *const _end_ptr = _base + _elems - 1;            \
  247.     QSORT_TYPE *_tmp_ptr = _base;                   \
  248.     register QSORT_TYPE *_run_ptr;                  \
  249.     QSORT_TYPE *_thresh;                        \
  250.                                     \
  251.     _thresh = _base + _QSORT_MAX_THRESH;                \
  252.     if (_thresh > _end_ptr)                     \
  253.       _thresh = _end_ptr;                       \
  254.                                     \
  255.     /* Find smallest element in first threshold and place it at the \
  256.        array's beginning.  This is the smallest array element,      \
  257.        and the operation speeds up insertion sort's inner loop. */  \
  258.                                     \
  259.     for (_run_ptr = _tmp_ptr + 1; _run_ptr <= _thresh; ++_run_ptr)  \
  260.       if (QSORT_LT (_run_ptr, _tmp_ptr))                \
  261.         _tmp_ptr = _run_ptr;                        \
  262.                                     \
  263.     if (_tmp_ptr != _base)                      \
  264.       _QSORT_SWAP (_tmp_ptr, _base, _hold);             \
  265.                                     \
  266.     /* Insertion sort, running from left-hand-side          \
  267.      * up to right-hand-side.  */                   \
  268.                                     \
  269.     _run_ptr = _base + 1;                       \
  270.     while (++_run_ptr <= _end_ptr) {                    \
  271.       _tmp_ptr = _run_ptr - 1;                      \
  272.       while (QSORT_LT (_run_ptr, _tmp_ptr))             \
  273.         --_tmp_ptr;                         \
  274.                                     \
  275.       ++_tmp_ptr;                           \
  276.       if (_tmp_ptr != _run_ptr) {                   \
  277.         QSORT_TYPE *_trav = _run_ptr + 1;               \
  278.         while (--_trav >= _run_ptr) {                   \
  279.           QSORT_TYPE *_hi; QSORT_TYPE *_lo;             \
  280.           _hold = *_trav;                       \
  281.                                     \
  282.           for (_hi = _lo = _trav; --_lo >= _tmp_ptr; _hi = _lo)     \
  283.             *_hi = *_lo;                        \
  284.           *_hi = _hold;                         \
  285.         }                               \
  286.       }                                 \
  287.     }                                   \
  288.   }                                 \
  289.                                     \
  290. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement