home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / misc / volume14 / lc / part01 / qsort.c < prev    next >
Encoding:
C/C++ Source or Header  |  1990-09-15  |  6.1 KB  |  222 lines

  1. /*
  2.  * Copyright (c) 1980 Regents of the University of California.
  3.  * All rights reserved.
  4.  *
  5.  * Redistribution and use in source and binary forms are permitted
  6.  * provided that the above copyright notice and this paragraph are
  7.  * duplicated in all such forms and that any documentation,
  8.  * advertising materials, and other materials related to such
  9.  * distribution and use acknowledge that the software was developed
  10.  * by the University of California, Berkeley.  The name of the
  11.  * University may not be used to endorse or promote products derived
  12.  * from this software without specific prior written permission.
  13.  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
  14.  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  15.  * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  16.  */
  17.  
  18. #if !defined(lint)
  19. static char sccsid[] = "@(#)qsort.c    5.4 (Berkeley) 6/27/88";
  20. #endif /* LIBC_SCCS and not lint */
  21.  
  22. /*
  23.  * qsort.c:
  24.  * Our own version of the system qsort routine which is faster by an average
  25.  * of 25%, with lows and highs of 10% and 50%.
  26.  * The THRESHold below is the insertion sort threshold, and has been adjusted
  27.  * for records of size 48 bytes.
  28.  * The MTHREShold is where we stop finding a better median.
  29.  */
  30.  
  31. #define        THRESH        4        /* threshold for insertion */
  32. #define        MTHRESH        6        /* threshold for median */
  33.  
  34. static  int        (*qcmp)();        /* the comparison routine */
  35. static  int        qsz;            /* size of each record */
  36. static  int        thresh;            /* THRESHold in chars */
  37. static  int        mthresh;        /* MTHRESHold in chars */
  38.  
  39. /*
  40.  * qst:
  41.  * Do a quicksort
  42.  * First, find the median element, and put that one in the first place as the
  43.  * discriminator.  (This "median" is just the median of the first, last and
  44.  * middle elements).  (Using this median instead of the first element is a big
  45.  * win).  Then, the usual partitioning/swapping, followed by moving the
  46.  * discriminator into the right place.  Then, figure out the sizes of the two
  47.  * partions, do the smaller one recursively and the larger one via a repeat of
  48.  * this code.  Stopping when there are less than THRESH elements in a partition
  49.  * and cleaning up with an insertion sort (in our caller) is a huge win.
  50.  * All data swaps are done in-line, which is space-losing but time-saving.
  51.  * (And there are only three places where this is done).
  52.  */
  53.  
  54. static void
  55. qst(base, max)
  56.     char *base, *max;
  57. {
  58.     register char c, *i, *j, *jj;
  59.     register int ii;
  60.     char *mid, *tmp;
  61.     int lo, hi;
  62.  
  63.     /*
  64.      * At the top here, lo is the number of characters of elements in the
  65.      * current partition.  (Which should be max - base).
  66.      * Find the median of the first, last, and middle element and make
  67.      * that the middle element.  Set j to largest of first and middle.
  68.      * If max is larger than that guy, then it's that guy, else compare
  69.      * max with loser of first and take larger.  Things are set up to
  70.      * prefer the middle, then the first in case of ties.
  71.      */
  72.     lo = max - base;        /* number of elements as chars */
  73.     do    {
  74.         mid = i = base + qsz * ((lo / qsz) >> 1);
  75.         if (lo >= mthresh) {
  76.             j = (qcmp((jj = base), i) > 0 ? jj : i);
  77.             if (qcmp(j, (tmp = max - qsz)) > 0) {
  78.                 /* switch to first loser */
  79.                 j = (j == jj ? i : jj);
  80.                 if (qcmp(j, tmp) < 0)
  81.                     j = tmp;
  82.             }
  83.             if (j != i) {
  84.                 ii = qsz;
  85.                 do    {
  86.                     c = *i;
  87.                     *i++ = *j;
  88.                     *j++ = c;
  89.                 } while (--ii);
  90.             }
  91.         }
  92.         /*
  93.          * Semi-standard quicksort partitioning/swapping
  94.          */
  95.         for (i = base, j = max - qsz; ; ) {
  96.             while (i < mid && qcmp(i, mid) <= 0)
  97.                 i += qsz;
  98.             while (j > mid) {
  99.                 if (qcmp(mid, j) <= 0) {
  100.                     j -= qsz;
  101.                     continue;
  102.                 }
  103.                 tmp = i + qsz;    /* value of i after swap */
  104.                 if (i == mid) {
  105.                     /* j <-> mid, new mid is j */
  106.                     mid = jj = j;
  107.                 } else {
  108.                     /* i <-> j */
  109.                     jj = j;
  110.                     j -= qsz;
  111.                 }
  112.                 goto swap;
  113.             }
  114.             if (i == mid) {
  115.                 break;
  116.             } else {
  117.                 /* i <-> mid, new mid is i */
  118.                 jj = mid;
  119.                 tmp = mid = i;    /* value of i after swap */
  120.                 j -= qsz;
  121.             }
  122.         swap:
  123.             ii = qsz;
  124.             do    {
  125.                 c = *i;
  126.                 *i++ = *jj;
  127.                 *jj++ = c;
  128.             } while (--ii);
  129.             i = tmp;
  130.         }
  131.         /*
  132.          * Look at sizes of the two partitions, do the smaller
  133.          * one first by recursion, then do the larger one by
  134.          * making sure lo is its size, base and max are update
  135.          * correctly, and branching back.  But only repeat
  136.          * (recursively or by branching) if the partition is
  137.          * of at least size THRESH.
  138.          */
  139.         i = (j = mid) + qsz;
  140.         if ((lo = j - base) <= (hi = max - i)) {
  141.             if (lo >= thresh)
  142.                 qst(base, j);
  143.             base = i;
  144.             lo = hi;
  145.         } else {
  146.             if (hi >= thresh)
  147.                 qst(i, max);
  148.             max = j;
  149.         }
  150.     } while (lo >= thresh);
  151.     return;
  152. }
  153.  
  154. /*
  155.  * qsort:
  156.  * First, set up some global parameters for qst to share.  Then, quicksort
  157.  * with qst(), and then a cleanup insertion sort ourselves.  Sound simple?
  158.  * It's not...
  159.  */
  160.  
  161. void
  162. qsort(base, n, size, compar)
  163.     char    *base;
  164.     int    n;
  165.     int    size;
  166.     int    (*compar)();
  167. {
  168.     register char c, *i, *j, *lo, *hi;
  169.     char *min, *max;
  170.  
  171.     if (n <= 1)
  172.         return;
  173.     qsz = size;
  174.     qcmp = compar;
  175.     thresh = qsz * THRESH;
  176.     mthresh = qsz * MTHRESH;
  177.     max = base + n * qsz;
  178.     if (n >= THRESH) {
  179.         qst(base, max);
  180.         hi = base + thresh;
  181.     } else {
  182.         hi = max;
  183.     }
  184.     /*
  185.      * First put smallest element, which must be in the first THRESH, in
  186.      * the first position as a sentinel.  This is done just by searching
  187.      * the first THRESH elements (or the first n if n < THRESH), finding
  188.      * the min, and swapping it into the first position.
  189.      */
  190.     for (j = lo = base; (lo += qsz) < hi; )
  191.         if (qcmp(j, lo) > 0)
  192.             j = lo;
  193.     if (j != base) {
  194.         /* swap j into place */
  195.         for (i = base, hi = base + qsz; i < hi; ) {
  196.             c = *j;
  197.             *j++ = *i;
  198.             *i++ = c;
  199.         }
  200.     }
  201.     /*
  202.      * With our sentinel in place, we now run the following hyper-fast
  203.      * insertion sort.  For each remaining element, min, from [1] to [n-1],
  204.      * set hi to the index of the element AFTER which this one goes.
  205.      * Then, do the standard insertion sort shift on a character at a time
  206.      * basis for each element in the frob.
  207.      */
  208.     for (min = base; (hi = min += qsz) < max; ) {
  209.         while (qcmp(hi -= qsz, min) > 0)
  210.             /* void */;
  211.         if ((hi += qsz) != min) {
  212.             for (lo = min + qsz; --lo >= min; ) {
  213.                 c = *lo;
  214.                 for (i = j = lo; (j -= qsz) >= hi; i = j)
  215.                     *i = *j;
  216.                 *i = c;
  217.             }
  218.         }
  219.     }
  220.     return;
  221. }
  222.