Leaked source code of windows server 2003
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

383 lines
13 KiB

  1. /***
  2. *qsort.c - quicksort algorithm; qsort() library function for sorting arrays
  3. *
  4. * Copyright (c) 1985-2001, Microsoft Corporation. All rights reserved.
  5. *
  6. *Purpose:
  7. * To implement the qsort() routine for sorting arrays.
  8. *
  9. *Revision History:
  10. * 06-22-84 RN author
  11. * 03-25-85 RN added pre-check for elements already in order to
  12. * eliminate worst-case behavior.
  13. * 05-18-86 TC changed to recurse on the smallest piece to avoid
  14. * piece. unneccesary stack usage, and to iterate on
  15. * largest
  16. * 01-09-87 BCM fixed huge-array case where (num-1) * wid computation
  17. * was overflowing (large/compact models only)
  18. * 06-13-89 PHG made more efficient, many more comments, removed
  19. * recursion
  20. * 10-30-89 JCR Added _cdecl to prototypes
  21. * 03-15-90 GJF Replaced _cdecl with _CALLTYPE1 and added #include
  22. * <cruntime.h>. Also, fixed the copyright.
  23. * 04-05-90 GJF Made shortsort() and swap() _CALLTYPE4. Also, added
  24. * #include <search.h>.
  25. * 10-04-90 GJF New-style function declarators.
  26. * 12-28-90 SRW Added _CRUISER_ conditional around check_stack pragmas
  27. * 01-24-91 SRW Added missing close comment in swap procedure
  28. * 11-19-91 GJF Do the swap one character at a time to avoid alignment
  29. * woes.
  30. * 04-06-93 SKS Replace _CRTAPI* with __cdecl
  31. * 09-06-94 CFW Remove Cruiser support.
  32. * 02-27-98 RKP Add 64 bit support.
  33. * 01-04-99 GJF Changes for 64-bit size_t.
  34. * 05-10-00 PML Performance improvements - middle-of-3 pivot choice,
  35. * widen middle range equal to pivot, don't swap pivot to
  36. * beginning (vs7#99674).
  37. * 08-08-00 PML Avoid calling comp(p,p), since some existing code
  38. * doesn't expect that (vs7#123134).
  39. *
  40. *******************************************************************************/
  41. #include <stdlib.h>
  42. #include <search.h>
  43. #ifdef NEW_QSORT_NAME
  44. #define qsort NEW_QSORT_NAME
  45. #endif
  46. /* Always compile this module for speed, not size */
  47. #pragma optimize("t", on)
  48. /* prototypes for local routines */
  49. static void __cdecl shortsort(char *lo, char *hi, size_t width,
  50. int (__cdecl *comp)(const void *, const void *));
  51. static void __cdecl swap(char *p, char *q, size_t width);
  52. /* this parameter defines the cutoff between using quick sort and
  53. insertion sort for arrays; arrays with lengths shorter or equal to the
  54. below value use insertion sort */
  55. #define CUTOFF 8 /* testing shows that this is good value */
  56. /***
  57. *qsort(base, num, wid, comp) - quicksort function for sorting arrays
  58. *
  59. *Purpose:
  60. * quicksort the array of elements
  61. * side effects: sorts in place
  62. * maximum array size is number of elements times size of elements,
  63. * but is limited by the virtual address space of the processor
  64. *
  65. *Entry:
  66. * char *base = pointer to base of array
  67. * size_t num = number of elements in the array
  68. * size_t width = width in bytes of each array element
  69. * int (*comp)() = pointer to function returning analog of strcmp for
  70. * strings, but supplied by user for comparing the array elements.
  71. * it accepts 2 pointers to elements and returns neg if 1<2, 0 if
  72. * 1=2, pos if 1>2.
  73. *
  74. *Exit:
  75. * returns void
  76. *
  77. *Exceptions:
  78. *
  79. *******************************************************************************/
  80. /* sort the array between lo and hi (inclusive) */
  81. #define STKSIZ (8*sizeof(void*) - 2)
  82. void __cdecl qsort (
  83. void *base,
  84. size_t num,
  85. size_t width,
  86. int (__cdecl *comp)(const void *, const void *)
  87. )
  88. {
  89. /* Note: the number of stack entries required is no more than
  90. 1 + log2(num), so 30 is sufficient for any array */
  91. char *lo, *hi; /* ends of sub-array currently sorting */
  92. char *mid; /* points to middle of subarray */
  93. char *loguy, *higuy; /* traveling pointers for partition step */
  94. size_t size; /* size of the sub-array */
  95. char *lostk[STKSIZ], *histk[STKSIZ];
  96. int stkptr; /* stack for saving sub-array to be processed */
  97. if (num < 2 || width == 0)
  98. return; /* nothing to do */
  99. stkptr = 0; /* initialize stack */
  100. lo = (char *)base;
  101. hi = (char *)base + width * (num-1); /* initialize limits */
  102. /* this entry point is for pseudo-recursion calling: setting
  103. lo and hi and jumping to here is like recursion, but stkptr is
  104. preserved, locals aren't, so we preserve stuff on the stack */
  105. recurse:
  106. size = (hi - lo) / width + 1; /* number of el's to sort */
  107. /* below a certain size, it is faster to use a O(n^2) sorting method */
  108. if (size <= CUTOFF) {
  109. shortsort(lo, hi, width, comp);
  110. }
  111. else {
  112. /* First we pick a partitioning element. The efficiency of the
  113. algorithm demands that we find one that is approximately the median
  114. of the values, but also that we select one fast. We choose the
  115. median of the first, middle, and last elements, to avoid bad
  116. performance in the face of already sorted data, or data that is made
  117. up of multiple sorted runs appended together. Testing shows that a
  118. median-of-three algorithm provides better performance than simply
  119. picking the middle element for the latter case. */
  120. mid = lo + (size / 2) * width; /* find middle element */
  121. /* Sort the first, middle, last elements into order */
  122. if (comp(lo, mid) > 0) {
  123. swap(lo, mid, width);
  124. }
  125. if (comp(lo, hi) > 0) {
  126. swap(lo, hi, width);
  127. }
  128. if (comp(mid, hi) > 0) {
  129. swap(mid, hi, width);
  130. }
  131. /* We now wish to partition the array into three pieces, one consisting
  132. of elements <= partition element, one of elements equal to the
  133. partition element, and one of elements > than it. This is done
  134. below; comments indicate conditions established at every step. */
  135. loguy = lo;
  136. higuy = hi;
  137. /* Note that higuy decreases and loguy increases on every iteration,
  138. so loop must terminate. */
  139. for (;;) {
  140. /* lo <= loguy < hi, lo < higuy <= hi,
  141. A[i] <= A[mid] for lo <= i <= loguy,
  142. A[i] > A[mid] for higuy <= i < hi,
  143. A[hi] >= A[mid] */
  144. /* The doubled loop is to avoid calling comp(mid,mid), since some
  145. existing comparison funcs don't work when passed the same
  146. value for both pointers. */
  147. if (mid > loguy) {
  148. do {
  149. loguy += width;
  150. } while (loguy < mid && comp(loguy, mid) <= 0);
  151. }
  152. if (mid <= loguy) {
  153. do {
  154. loguy += width;
  155. } while (loguy <= hi && comp(loguy, mid) <= 0);
  156. }
  157. /* lo < loguy <= hi+1, A[i] <= A[mid] for lo <= i < loguy,
  158. either loguy > hi or A[loguy] > A[mid] */
  159. do {
  160. higuy -= width;
  161. } while (higuy > mid && comp(higuy, mid) > 0);
  162. /* lo <= higuy < hi, A[i] > A[mid] for higuy < i < hi,
  163. either higuy == lo or A[higuy] <= A[mid] */
  164. if (higuy < loguy)
  165. break;
  166. /* if loguy > hi or higuy == lo, then we would have exited, so
  167. A[loguy] > A[mid], A[higuy] <= A[mid],
  168. loguy <= hi, higuy > lo */
  169. swap(loguy, higuy, width);
  170. /* If the partition element was moved, follow it. Only need
  171. to check for mid == higuy, since before the swap,
  172. A[loguy] > A[mid] implies loguy != mid. */
  173. if (mid == higuy)
  174. mid = loguy;
  175. /* A[loguy] <= A[mid], A[higuy] > A[mid]; so condition at top
  176. of loop is re-established */
  177. }
  178. /* A[i] <= A[mid] for lo <= i < loguy,
  179. A[i] > A[mid] for higuy < i < hi,
  180. A[hi] >= A[mid]
  181. higuy < loguy
  182. implying:
  183. higuy == loguy-1
  184. or higuy == hi - 1, loguy == hi + 1, A[hi] == A[mid] */
  185. /* Find adjacent elements equal to the partition element. The
  186. doubled loop is to avoid calling comp(mid,mid), since some
  187. existing comparison funcs don't work when passed the same value
  188. for both pointers. */
  189. higuy += width;
  190. if (mid < higuy) {
  191. do {
  192. higuy -= width;
  193. } while (higuy > mid && comp(higuy, mid) == 0);
  194. }
  195. if (mid >= higuy) {
  196. do {
  197. higuy -= width;
  198. } while (higuy > lo && comp(higuy, mid) == 0);
  199. }
  200. /* OK, now we have the following:
  201. higuy < loguy
  202. lo <= higuy <= hi
  203. A[i] <= A[mid] for lo <= i <= higuy
  204. A[i] == A[mid] for higuy < i < loguy
  205. A[i] > A[mid] for loguy <= i < hi
  206. A[hi] >= A[mid] */
  207. /* We've finished the partition, now we want to sort the subarrays
  208. [lo, higuy] and [loguy, hi].
  209. We do the smaller one first to minimize stack usage.
  210. We only sort arrays of length 2 or more.*/
  211. if ( higuy - lo >= hi - loguy ) {
  212. if (lo < higuy) {
  213. lostk[stkptr] = lo;
  214. histk[stkptr] = higuy;
  215. ++stkptr;
  216. } /* save big recursion for later */
  217. if (loguy < hi) {
  218. lo = loguy;
  219. goto recurse; /* do small recursion */
  220. }
  221. }
  222. else {
  223. if (loguy < hi) {
  224. lostk[stkptr] = loguy;
  225. histk[stkptr] = hi;
  226. ++stkptr; /* save big recursion for later */
  227. }
  228. if (lo < higuy) {
  229. hi = higuy;
  230. goto recurse; /* do small recursion */
  231. }
  232. }
  233. }
  234. /* We have sorted the array, except for any pending sorts on the stack.
  235. Check if there are any, and do them. */
  236. --stkptr;
  237. if (stkptr >= 0) {
  238. lo = lostk[stkptr];
  239. hi = histk[stkptr];
  240. goto recurse; /* pop subarray from stack */
  241. }
  242. else
  243. return; /* all subarrays done */
  244. }
  245. /***
  246. *shortsort(hi, lo, width, comp) - insertion sort for sorting short arrays
  247. *
  248. *Purpose:
  249. * sorts the sub-array of elements between lo and hi (inclusive)
  250. * side effects: sorts in place
  251. * assumes that lo < hi
  252. *
  253. *Entry:
  254. * char *lo = pointer to low element to sort
  255. * char *hi = pointer to high element to sort
  256. * size_t width = width in bytes of each array element
  257. * int (*comp)() = pointer to function returning analog of strcmp for
  258. * strings, but supplied by user for comparing the array elements.
  259. * it accepts 2 pointers to elements and returns neg if 1<2, 0 if
  260. * 1=2, pos if 1>2.
  261. *
  262. *Exit:
  263. * returns void
  264. *
  265. *Exceptions:
  266. *
  267. *******************************************************************************/
  268. static void __cdecl shortsort (
  269. char *lo,
  270. char *hi,
  271. size_t width,
  272. int (__cdecl *comp)(const void *, const void *)
  273. )
  274. {
  275. char *p, *max;
  276. /* Note: in assertions below, i and j are alway inside original bound of
  277. array to sort. */
  278. while (hi > lo) {
  279. /* A[i] <= A[j] for i <= j, j > hi */
  280. max = lo;
  281. for (p = lo+width; p <= hi; p += width) {
  282. /* A[i] <= A[max] for lo <= i < p */
  283. if (comp(p, max) > 0) {
  284. max = p;
  285. }
  286. /* A[i] <= A[max] for lo <= i <= p */
  287. }
  288. /* A[i] <= A[max] for lo <= i <= hi */
  289. swap(max, hi, width);
  290. /* A[i] <= A[hi] for i <= hi, so A[i] <= A[j] for i <= j, j >= hi */
  291. hi -= width;
  292. /* A[i] <= A[j] for i <= j, j > hi, loop top condition established */
  293. }
  294. /* A[i] <= A[j] for i <= j, j > lo, which implies A[i] <= A[j] for i < j,
  295. so array is sorted */
  296. }
  297. /***
  298. *swap(a, b, width) - swap two elements
  299. *
  300. *Purpose:
  301. * swaps the two array elements of size width
  302. *
  303. *Entry:
  304. * char *a, *b = pointer to two elements to swap
  305. * size_t width = width in bytes of each array element
  306. *
  307. *Exit:
  308. * returns void
  309. *
  310. *Exceptions:
  311. *
  312. *******************************************************************************/
  313. static void __cdecl swap (
  314. char *a,
  315. char *b,
  316. size_t width
  317. )
  318. {
  319. char tmp;
  320. if ( a != b )
  321. /* Do the swap one character at a time to avoid potential alignment
  322. problems. */
  323. while ( width-- ) {
  324. tmp = *a;
  325. *a++ = *b;
  326. *b++ = tmp;
  327. }
  328. }