Guest User

JTE

a guest
Sep 1st, 2011
396
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 13.38 KB | None | 0 0
  1. /***
  2. *qsort.c - quicksort algorithm; qsort() library function for sorting arrays
  3. *
  4. *   Copyright (c) Microsoft Corporation. All rights reserved.
  5. *
  6. *Purpose:
  7. *   To implement the qsort() routine for sorting arrays.
  8. *
  9. *******************************************************************************/
  10.  
  11. #include <stdlib.h>
  12. #include <search.h>
  13. #include <internal.h>
  14.  
  15. /* Always compile this module for speed, not size */
  16. #pragma optimize("t", on)
  17.  
  18. #if defined (_M_CEE)
  19. #define __fileDECL  __clrcall
  20. #else  /* defined (_M_CEE) */
  21. #define __fileDECL  __cdecl
  22. #endif  /* defined (_M_CEE) */
  23.  
  24. /* when building Managed Run time dll, we should be defining __cdecl
  25.  * to __clrcall. Also note that when compiling for MRT, we are compiling
  26.  * as C++ file.
  27.  */
  28.  
  29. /* prototypes for local routines */
  30. #ifdef __USE_CONTEXT
  31. static void __fileDECL shortsort_s(char *lo, char *hi, size_t width,
  32.                 int (__fileDECL *comp)(void *, const void *, const void *), void *);
  33. #define swap swap_c
  34. #else  /* __USE_CONTEXT */
  35. static void __fileDECL shortsort(char *lo, char *hi, size_t width,
  36.                 int (__fileDECL *comp)(const void *, const void *));
  37. #endif  /* __USE_CONTEXT */
  38.  
  39. static void __fileDECL swap(char *p, char *q, size_t width);
  40.  
  41. /* this parameter defines the cutoff between using quick sort and
  42.    insertion sort for arrays; arrays with lengths shorter or equal to the
  43.    below value use insertion sort */
  44.  
  45. #define CUTOFF 8            /* testing shows that this is good value */
  46.  
  47. /* Note: the theoretical number of stack entries required is
  48.    no more than 1 + log2(num).  But we switch to insertion
  49.    sort for CUTOFF elements or less, so we really only need
  50.    1 + log2(num) - log2(CUTOFF) stack entries.  For a CUTOFF
  51.    of 8, that means we need no more than 30 stack entries for
  52.    32 bit platforms, and 62 for 64-bit platforms. */
  53. #define STKSIZ (8*sizeof(void*) - 2)
  54.  
  55. /***
  56. *qsort(base, num, wid, comp) - quicksort function for sorting arrays
  57. *
  58. *Purpose:
  59. *   quicksort the array of elements
  60. *   side effects:  sorts in place
  61. *   maximum array size is number of elements times size of elements,
  62. *   but is limited by the virtual address space of the processor
  63. *
  64. *Entry:
  65. *   char *base = pointer to base of array
  66. *   size_t num  = number of elements in the array
  67. *   size_t width = width in bytes of each array element
  68. *   int (*comp)() = pointer to function returning analog of strcmp for
  69. *           strings, but supplied by user for comparing the array elements.
  70. *           it accepts 2 pointers to elements.
  71. *           Returns neg if 1<2, 0 if 1=2, pos if 1>2.
  72. *
  73. *Exit:
  74. *   returns void
  75. *
  76. *Exceptions:
  77. *   Input parameters are validated. Refer to the validation section of the function.
  78. *
  79. *******************************************************************************/
  80.  
  81. #ifdef __USE_CONTEXT
  82. #define __COMPARE(context, p1, p2) comp(context, p1, p2)
  83. #define __SHORTSORT(lo, hi, width, comp, context) shortsort_s(lo, hi, width, comp, context);
  84. #else  /* __USE_CONTEXT */
  85. #define __COMPARE(context, p1, p2) comp(p1, p2)
  86. #define __SHORTSORT(lo, hi, width, comp, context) shortsort(lo, hi, width, comp);
  87. #endif  /* __USE_CONTEXT */
  88.  
  89. SECURITYSAFECRITICAL_ATTRIBUTE
  90. #ifdef __USE_CONTEXT
  91. void __fileDECL qsort_s (
  92.     void *base,
  93.     size_t num,
  94.     size_t width,
  95.     int (__fileDECL *comp)(void *, const void *, const void *),
  96.     void *context
  97.     )
  98. #else  /* __USE_CONTEXT */
  99. void __fileDECL qsort (
  100.     void *base,
  101.     size_t num,
  102.     size_t width,
  103.     int (__fileDECL *comp)(const void *, const void *)
  104.     )
  105. #endif  /* __USE_CONTEXT */
  106. {
  107.     char *lo, *hi;              /* ends of sub-array currently sorting */
  108.     char *mid;                  /* points to middle of subarray */
  109.     char *loguy, *higuy;        /* traveling pointers for partition step */
  110.     size_t size;                /* size of the sub-array */
  111.     char *lostk[STKSIZ], *histk[STKSIZ];
  112.     int stkptr;                 /* stack for saving sub-array to be processed */
  113.  
  114.     /* validation section */
  115.     _VALIDATE_RETURN_VOID(base != NULL || num == 0, EINVAL);
  116.     _VALIDATE_RETURN_VOID(width > 0, EINVAL);
  117.     _VALIDATE_RETURN_VOID(comp != NULL, EINVAL);
  118.  
  119.     if (num < 2)
  120.         return;                 /* nothing to do */
  121.  
  122.     stkptr = 0;                 /* initialize stack */
  123.  
  124.     lo = (char *)base;
  125.     hi = (char *)base + width * (num-1);        /* initialize limits */
  126.  
  127.     /* this entry point is for pseudo-recursion calling: setting
  128.        lo and hi and jumping to here is like recursion, but stkptr is
  129.        preserved, locals aren't, so we preserve stuff on the stack */
  130. recurse:
  131.  
  132.     size = (hi - lo) / width + 1;        /* number of el's to sort */
  133.  
  134.     /* below a certain size, it is faster to use a O(n^2) sorting method */
  135.     if (size <= CUTOFF) {
  136.         __SHORTSORT(lo, hi, width, comp, context);
  137.     }
  138.     else {
  139.         /* First we pick a partitioning element.  The efficiency of the
  140.            algorithm demands that we find one that is approximately the median
  141.            of the values, but also that we select one fast.  We choose the
  142.            median of the first, middle, and last elements, to avoid bad
  143.            performance in the face of already sorted data, or data that is made
  144.            up of multiple sorted runs appended together.  Testing shows that a
  145.            median-of-three algorithm provides better performance than simply
  146.            picking the middle element for the latter case. */
  147.  
  148.         mid = lo + (size / 2) * width;      /* find middle element */
  149.  
  150.         /* Sort the first, middle, last elements into order */
  151.         if (__COMPARE(context, lo, mid) > 0) {
  152.             swap(lo, mid, width);
  153.         }
  154.         if (__COMPARE(context, lo, hi) > 0) {
  155.             swap(lo, hi, width);
  156.         }
  157.         if (__COMPARE(context, mid, hi) > 0) {
  158.             swap(mid, hi, width);
  159.         }
  160.  
  161.         /* We now wish to partition the array into three pieces, one consisting
  162.            of elements <= partition element, one of elements equal to the
  163.            partition element, and one of elements > than it.  This is done
  164.            below; comments indicate conditions established at every step. */
  165.  
  166.         loguy = lo;
  167.         higuy = hi;
  168.  
  169.         /* Note that higuy decreases and loguy increases on every iteration,
  170.            so loop must terminate. */
  171.         for (;;) {
  172.             /* lo <= loguy < hi, lo < higuy <= hi,
  173.                A[i] <= A[mid] for lo <= i <= loguy,
  174.                A[i] > A[mid] for higuy <= i < hi,
  175.                A[hi] >= A[mid] */
  176.  
  177.             /* The doubled loop is to avoid calling comp(mid,mid), since some
  178.                existing comparison funcs don't work when passed the same
  179.                value for both pointers. */
  180.  
  181.             if (mid > loguy) {
  182.                 do  {
  183.                     loguy += width;
  184.                 } while (loguy < mid && __COMPARE(context, loguy, mid) <= 0);
  185.             }
  186.             if (mid <= loguy) {
  187.                 do  {
  188.                     loguy += width;
  189.                 } while (loguy <= hi && __COMPARE(context, loguy, mid) <= 0);
  190.             }
  191.  
  192.             /* lo < loguy <= hi+1, A[i] <= A[mid] for lo <= i < loguy,
  193.                either loguy > hi or A[loguy] > A[mid] */
  194.  
  195.             do  {
  196.                 higuy -= width;
  197.             } while (higuy > mid && __COMPARE(context, higuy, mid) > 0);
  198.  
  199.             /* lo <= higuy < hi, A[i] > A[mid] for higuy < i < hi,
  200.                either higuy == lo or A[higuy] <= A[mid] */
  201.  
  202.             if (higuy < loguy)
  203.                 break;
  204.  
  205.             /* if loguy > hi or higuy == lo, then we would have exited, so
  206.                A[loguy] > A[mid], A[higuy] <= A[mid],
  207.                loguy <= hi, higuy > lo */
  208.  
  209.             swap(loguy, higuy, width);
  210.  
  211.             /* If the partition element was moved, follow it.  Only need
  212.                to check for mid == higuy, since before the swap,
  213.                A[loguy] > A[mid] implies loguy != mid. */
  214.  
  215.             if (mid == higuy)
  216.                 mid = loguy;
  217.  
  218.             /* A[loguy] <= A[mid], A[higuy] > A[mid]; so condition at top
  219.                of loop is re-established */
  220.         }
  221.  
  222.         /*     A[i] <= A[mid] for lo <= i < loguy,
  223.                A[i] > A[mid] for higuy < i < hi,
  224.                A[hi] >= A[mid]
  225.                higuy < loguy
  226.            implying:
  227.                higuy == loguy-1
  228.                or higuy == hi - 1, loguy == hi + 1, A[hi] == A[mid] */
  229.  
  230.         /* Find adjacent elements equal to the partition element.  The
  231.            doubled loop is to avoid calling comp(mid,mid), since some
  232.            existing comparison funcs don't work when passed the same value
  233.            for both pointers. */
  234.  
  235.         higuy += width;
  236.         if (mid < higuy) {
  237.             do  {
  238.                 higuy -= width;
  239.             } while (higuy > mid && __COMPARE(context, higuy, mid) == 0);
  240.         }
  241.         if (mid >= higuy) {
  242.             do  {
  243.                 higuy -= width;
  244.             } while (higuy > lo && __COMPARE(context, higuy, mid) == 0);
  245.         }
  246.  
  247.         /* OK, now we have the following:
  248.               higuy < loguy
  249.               lo <= higuy <= hi
  250.               A[i]  <= A[mid] for lo <= i <= higuy
  251.               A[i]  == A[mid] for higuy < i < loguy
  252.               A[i]  >  A[mid] for loguy <= i < hi
  253.               A[hi] >= A[mid] */
  254.  
  255.         /* We've finished the partition, now we want to sort the subarrays
  256.            [lo, higuy] and [loguy, hi].
  257.            We do the smaller one first to minimize stack usage.
  258.            We only sort arrays of length 2 or more.*/
  259.  
  260.         if ( higuy - lo >= hi - loguy ) {
  261.             if (lo < higuy) {
  262.                 lostk[stkptr] = lo;
  263.                 histk[stkptr] = higuy;
  264.                 ++stkptr;
  265.             }                           /* save big recursion for later */
  266.  
  267.             if (loguy < hi) {
  268.                 lo = loguy;
  269.                 goto recurse;           /* do small recursion */
  270.             }
  271.         }
  272.         else {
  273.             if (loguy < hi) {
  274.                 lostk[stkptr] = loguy;
  275.                 histk[stkptr] = hi;
  276.                 ++stkptr;               /* save big recursion for later */
  277.             }
  278.  
  279.             if (lo < higuy) {
  280.                 hi = higuy;
  281.                 goto recurse;           /* do small recursion */
  282.             }
  283.         }
  284.     }
  285.  
  286.     /* We have sorted the array, except for any pending sorts on the stack.
  287.        Check if there are any, and do them. */
  288.  
  289.     --stkptr;
  290.     if (stkptr >= 0) {
  291.         lo = lostk[stkptr];
  292.         hi = histk[stkptr];
  293.         goto recurse;           /* pop subarray from stack */
  294.     }
  295.     else
  296.         return;                 /* all subarrays done */
  297. }
  298.  
  299.  
  300. /***
  301. *shortsort(hi, lo, width, comp) - insertion sort for sorting short arrays
  302. *shortsort_s(hi, lo, width, comp, context) - insertion sort for sorting short arrays
  303. *
  304. *Purpose:
  305. *       sorts the sub-array of elements between lo and hi (inclusive)
  306. *       side effects:  sorts in place
  307. *       assumes that lo < hi
  308. *
  309. *Entry:
  310. *       char *lo = pointer to low element to sort
  311. *       char *hi = pointer to high element to sort
  312. *       size_t width = width in bytes of each array element
  313. *       int (*comp)() = pointer to function returning analog of strcmp for
  314. *               strings, but supplied by user for comparing the array elements.
  315. *               it accepts 2 pointers to elements, together with a pointer to a context
  316. *               (if present). Returns neg if 1<2, 0 if 1=2, pos if 1>2.
  317. *       void *context - pointer to the context in which the function is
  318. *               called. This context is passed to the comparison function.
  319. *
  320. *Exit:
  321. *       returns void
  322. *
  323. *Exceptions:
  324. *
  325. *******************************************************************************/
  326.  
  327. SECURITYSAFECRITICAL_ATTRIBUTE
  328. #ifdef __USE_CONTEXT
  329. static void __fileDECL shortsort_s (
  330.     char *lo,
  331.     char *hi,
  332.     size_t width,
  333.     int (__fileDECL *comp)(void *, const void *, const void *),
  334.     void * context
  335.     )
  336. #else  /* __USE_CONTEXT */
  337. static void __fileDECL shortsort (
  338.     char *lo,
  339.     char *hi,
  340.     size_t width,
  341.     int (__fileDECL *comp)(const void *, const void *)
  342.     )
  343. #endif  /* __USE_CONTEXT */
  344. {
  345.     char *p, *max;
  346.  
  347.     /* Note: in assertions below, i and j are alway inside original bound of
  348.        array to sort. */
  349.  
  350.     while (hi > lo) {
  351.         /* A[i] <= A[j] for i <= j, j > hi */
  352.         max = lo;
  353.         for (p = lo+width; p <= hi; p += width) {
  354.             /* A[i] <= A[max] for lo <= i < p */
  355.             if (__COMPARE(context, p, max) > 0) {
  356.                 max = p;
  357.             }
  358.             /* A[i] <= A[max] for lo <= i <= p */
  359.         }
  360.  
  361.         /* A[i] <= A[max] for lo <= i <= hi */
  362.  
  363.         swap(max, hi, width);
  364.  
  365.         /* A[i] <= A[hi] for i <= hi, so A[i] <= A[j] for i <= j, j >= hi */
  366.  
  367.         hi -= width;
  368.  
  369.         /* A[i] <= A[j] for i <= j, j > hi, loop top condition established */
  370.     }
  371.     /* A[i] <= A[j] for i <= j, j > lo, which implies A[i] <= A[j] for i < j,
  372.        so array is sorted */
  373. }
  374.  
  375. /***
  376. *swap(a, b, width) - swap two elements
  377. *
  378. *Purpose:
  379. *       swaps the two array elements of size width
  380. *
  381. *Entry:
  382. *       char *a, *b = pointer to two elements to swap
  383. *       size_t width = width in bytes of each array element
  384. *
  385. *Exit:
  386. *       returns void
  387. *
  388. *Exceptions:
  389. *
  390. *******************************************************************************/
  391.  
  392. SECURITYSAFECRITICAL_ATTRIBUTE
  393. static void __fileDECL swap (
  394.     char *a,
  395.     char *b,
  396.     size_t width
  397.     )
  398. {
  399.     char tmp;
  400.  
  401.     if ( a != b )
  402.         /* Do the swap one character at a time to avoid potential alignment
  403.            problems. */
  404.         while ( width-- ) {
  405.             tmp = *a;
  406.             *a++ = *b;
  407.             *b++ = tmp;
  408.         }
  409. }
  410.  
  411. #undef __fileDECL
  412. #undef __COMPARE
  413. #undef __SHORTSORT
  414. #undef swap
Advertisement
Add Comment
Please, Sign In to add comment