quicksort.c
上传用户:shenzhenrh
上传日期:2013-05-12
资源大小:2904k
文件大小:8k
源码类别:

信息检索与抽取

开发平台:

Unix_Linux

  1. /* Copyright (C) 1991, 1992, 1996, 1997 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.    The GNU C Library is free software; you can redistribute it and/or
  5.    modify it under the terms of the GNU Library General Public License as
  6.    published by the Free Software Foundation; either version 2 of the
  7.    License, or (at your option) any later version.
  8.    The GNU C Library is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  11.    Library General Public License for more details.
  12.    You should have received a copy of the GNU Library General Public
  13.    License along with the GNU C Library; see the file COPYING.LIB.  If not,
  14.    write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  15.    Boston, MA 02111-1307, USA.  */
  16. #include <misc.h>
  17. /* Byte-wise swap two items of size SIZE. */
  18. #define SWAP(a, b, size)       
  19.   do       
  20.     {       
  21.       register size_t __size = (size);       
  22.       register char *__a = (a), *__b = (b);       
  23.       do       
  24. {       
  25.   char __tmp = *__a;       
  26.   *__a++ = *__b;       
  27.   *__b++ = __tmp;       
  28. } while (--__size > 0);       
  29.     } while (0)
  30. /* Discontinue quicksort algorithm when partition gets below this size.
  31.    This particular magic number was chosen to work best on a Sun 4/260. */
  32. #define MAX_THRESH 4
  33. /* Stack node declarations used to store unfulfilled partition obligations. */
  34. typedef struct
  35.   {
  36.     char *lo;
  37.     char *hi;
  38.   } stack_node;
  39. /* The next 4 #defines implement a very fast in-line stack abstraction. */
  40. #define STACK_SIZE (8 * sizeof(unsigned long int))
  41. #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
  42. #define POP(low, high) ((void) (--top, (low = top->lo), (high = top->hi)))
  43. #define STACK_NOT_EMPTY (stack < top)
  44. /* Order size using quicksort.  This implementation incorporates
  45.    four optimizations discussed in Sedgewick:
  46.    1. Non-recursive, using an explicit stack of pointer that store the
  47.       next array partition to sort.  To save time, this maximum amount
  48.       of space required to store an array of MAX_INT is allocated on the
  49.       stack.  Assuming a 32-bit integer, this needs only 32 *
  50.       sizeof(stack_node) == 136 bits.  Pretty cheap, actually.
  51.    2. Chose the pivot element using a median-of-three decision tree.
  52.       This reduces the probability of selecting a bad pivot value and
  53.       eliminates certain extraneous comparisons.
  54.    3. Only quicksorts TOTAL_ELEMS / MAX_THRESH partitions, leaving
  55.       insertion sort to order the MAX_THRESH items within each partition.
  56.       This is a big win, since insertion sort is faster for small, mostly
  57.       sorted array segments.
  58.    4. The larger of the two sub-partitions is always pushed onto the
  59.       stack first, with the algorithm then concentrating on the
  60.       smaller partition.  This *guarantees* no more than log (n)
  61.       stack size is needed (actually O(1) in this case)!  */
  62. void
  63. quicksort (pbase, total_elems, size, cmp)
  64.            void *const pbase;
  65.            size_t total_elems;
  66.            size_t size;
  67.            quicksort_compar_fn_t cmp;
  68. {
  69.   register char *base_ptr = (char *) pbase;
  70.   /* Allocating SIZE bytes for a pivot buffer facilitates a better
  71.      algorithm below since we can do comparisons directly on the pivot. */
  72.   char pivot_buffer[size];
  73.   const size_t max_thresh = MAX_THRESH * size;
  74.   if (total_elems == 0)
  75.     /* Avoid lossage with unsigned arithmetic below.  */
  76.     return;
  77.   if (total_elems > MAX_THRESH)
  78.     {
  79.       char *lo = base_ptr;
  80.       char *hi = &lo[size * (total_elems - 1)];
  81.       /* Largest size needed for 32-bit int!!! */
  82.       stack_node stack[STACK_SIZE];
  83.       stack_node *top = stack + 1;
  84.       while (STACK_NOT_EMPTY)
  85.         {
  86.           char *left_ptr;
  87.           char *right_ptr;
  88.   char *pivot = pivot_buffer;
  89.   /* Select median value from among LO, MID, and HI. Rearrange
  90.      LO and HI so the three values are sorted. This lowers the
  91.      probability of picking a pathological pivot value and
  92.      skips a comparison for both the LEFT_PTR and RIGHT_PTR. */
  93.   char *mid = lo + size * ((hi - lo) / size >> 1);
  94.   if ((*cmp) ((void *) mid, (void *) lo) < 0)
  95.     SWAP (mid, lo, size);
  96.   if ((*cmp) ((void *) hi, (void *) mid) < 0)
  97.     SWAP (mid, hi, size);
  98.   else
  99.     goto jump_over;
  100.   if ((*cmp) ((void *) mid, (void *) lo) < 0)
  101.     SWAP (mid, lo, size);
  102. jump_over:;
  103.   memcpy (pivot, mid, size);
  104.   pivot = pivot_buffer;
  105.   left_ptr  = lo + size;
  106.   right_ptr = hi - size;
  107.   /* Here's the famous ``collapse the walls'' section of quicksort.
  108.      Gotta like those tight inner loops!  They are the main reason
  109.      that this algorithm runs much faster than others. */
  110.   do
  111.     {
  112.       while ((*cmp) ((void *) left_ptr, (void *) pivot) < 0)
  113. left_ptr += size;
  114.       while ((*cmp) ((void *) pivot, (void *) right_ptr) < 0)
  115. right_ptr -= size;
  116.       if (left_ptr < right_ptr)
  117. {
  118.   SWAP (left_ptr, right_ptr, size);
  119.   left_ptr += size;
  120.   right_ptr -= size;
  121. }
  122.       else if (left_ptr == right_ptr)
  123. {
  124.   left_ptr += size;
  125.   right_ptr -= size;
  126.   break;
  127. }
  128.     }
  129.   while (left_ptr <= right_ptr);
  130.           /* Set up pointers for next iteration.  First determine whether
  131.              left and right partitions are below the threshold size.  If so,
  132.              ignore one or both.  Otherwise, push the larger partition's
  133.              bounds on the stack and continue sorting the smaller one. */
  134.           if ((size_t) (right_ptr - lo) <= max_thresh)
  135.             {
  136.               if ((size_t) (hi - left_ptr) <= max_thresh)
  137. /* Ignore both small partitions. */
  138.                 POP (lo, hi);
  139.               else
  140. /* Ignore small left partition. */
  141.                 lo = left_ptr;
  142.             }
  143.           else if ((size_t) (hi - left_ptr) <= max_thresh)
  144.     /* Ignore small right partition. */
  145.             hi = right_ptr;
  146.           else if ((right_ptr - lo) > (hi - left_ptr))
  147.             {
  148.       /* Push larger left partition indices. */
  149.               PUSH (lo, right_ptr);
  150.               lo = left_ptr;
  151.             }
  152.           else
  153.             {
  154.       /* Push larger right partition indices. */
  155.               PUSH (left_ptr, hi);
  156.               hi = right_ptr;
  157.             }
  158.         }
  159.     }
  160.   /* Once the BASE_PTR array is partially sorted by quicksort the rest
  161.      is completely sorted using insertion sort, since this is efficient
  162.      for partitions below MAX_THRESH size. BASE_PTR points to the beginning
  163.      of the array to sort, and END_PTR points at the very last element in
  164.      the array (*not* one beyond it!). */
  165. #define min(x, y) ((x) < (y) ? (x) : (y))
  166.   {
  167.     char *const end_ptr = &base_ptr[size * (total_elems - 1)];
  168.     char *tmp_ptr = base_ptr;
  169.     char *thresh = min(end_ptr, base_ptr + max_thresh);
  170.     register char *run_ptr;
  171.     /* Find smallest element in first threshold and place it at the
  172.        array's beginning.  This is the smallest array element,
  173.        and the operation speeds up insertion sort's inner loop. */
  174.     for (run_ptr = tmp_ptr + size; run_ptr <= thresh; run_ptr += size)
  175.       if ((*cmp) ((void *) run_ptr, (void *) tmp_ptr) < 0)
  176.         tmp_ptr = run_ptr;
  177.     if (tmp_ptr != base_ptr)
  178.       SWAP (tmp_ptr, base_ptr, size);
  179.     /* Insertion sort, running from left-hand-side up to right-hand-side.  */
  180.     run_ptr = base_ptr + size;
  181.     while ((run_ptr += size) <= end_ptr)
  182.       {
  183. tmp_ptr = run_ptr - size;
  184. while ((*cmp) ((void *) run_ptr, (void *) tmp_ptr) < 0)
  185.   tmp_ptr -= size;
  186. tmp_ptr += size;
  187.         if (tmp_ptr != run_ptr)
  188.           {
  189.             char *trav;
  190.     trav = run_ptr + size;
  191.     while (--trav >= run_ptr)
  192.               {
  193.                 char c = *trav;
  194.                 char *hi, *lo;
  195.                 for (hi = lo = trav; (lo -= size) >= tmp_ptr; hi = lo)
  196.                   *hi = *lo;
  197.                 *hi = c;
  198.               }
  199.           }
  200.       }
  201.   }
  202. }