SDL_qsort.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2016 Sam Lantinga <slouken@libsdl.org>
  4. This software is provided 'as-is', without any express or implied
  5. warranty. In no event will the authors be held liable for any damages
  6. arising from the use of this software.
  7. Permission is granted to anyone to use this software for any purpose,
  8. including commercial applications, and to alter it and redistribute it
  9. freely, subject to the following restrictions:
  10. 1. The origin of this software must not be misrepresented; you must not
  11. claim that you wrote the original software. If you use this software
  12. in a product, an acknowledgment in the product documentation would be
  13. appreciated but is not required.
  14. 2. Altered source versions must be plainly marked as such, and must not be
  15. misrepresented as being the original software.
  16. 3. This notice may not be removed or altered from any source distribution.
  17. */
  18. #if defined(__clang_analyzer__) && !defined(SDL_DISABLE_ANALYZE_MACROS)
  19. #define SDL_DISABLE_ANALYZE_MACROS 1
  20. #endif
  21. #include "../SDL_internal.h"
  22. #include "SDL_stdinc.h"
  23. #include "SDL_assert.h"
  24. #if defined(HAVE_QSORT)
  25. void
  26. SDL_qsort(void *base, size_t nmemb, size_t size, int (*compare) (const void *, const void *))
  27. {
  28. qsort(base, nmemb, size, compare);
  29. }
  30. #else
  31. #ifdef assert
  32. #undef assert
  33. #endif
  34. #define assert SDL_assert
  35. #ifdef malloc
  36. #undef malloc
  37. #endif
  38. #define malloc SDL_malloc
  39. #ifdef free
  40. #undef free
  41. #endif
  42. #define free SDL_free
  43. #ifdef memcpy
  44. #undef memcpy
  45. #endif
  46. #define memcpy SDL_memcpy
  47. #ifdef memmove
  48. #undef memmove
  49. #endif
  50. #define memmove SDL_memmove
  51. #ifdef qsortG
  52. #undef qsortG
  53. #endif
  54. #define qsortG SDL_qsort
  55. /*
  56. This code came from Gareth McCaughan, under the zlib license.
  57. Specifically this: https://www.mccaughan.org.uk/software/qsort.c-1.14
  58. Everything below this comment until the HAVE_QSORT #endif was from Gareth
  59. (any minor changes will be noted inline).
  60. Thank you to Gareth for relicensing this code under the zlib license for our
  61. benefit!
  62. --ryan.
  63. */
  64. /* This is a drop-in replacement for the C library's |qsort()| routine.
  65. *
  66. * It is intended for use where you know or suspect that your
  67. * platform's qsort is bad. If that isn't the case, then you
  68. * should probably use the qsort your system gives you in preference
  69. * to mine -- it will likely have been tested and tuned better.
  70. *
  71. * Features:
  72. * - Median-of-three pivoting (and more)
  73. * - Truncation and final polishing by a single insertion sort
  74. * - Early truncation when no swaps needed in pivoting step
  75. * - Explicit recursion, guaranteed not to overflow
  76. * - A few little wrinkles stolen from the GNU |qsort()|.
  77. * (For the avoidance of doubt, no code was stolen, only
  78. * broad ideas.)
  79. * - separate code for non-aligned / aligned / word-size objects
  80. *
  81. * Earlier releases of this code used an idiosyncratic licence
  82. * I wrote myself, because I'm an idiot. The code is now released
  83. * under the "zlib/libpng licence"; you will find the actual
  84. * terms in the next comment. I request (but do not require)
  85. * that if you make any changes beyond the name of the exported
  86. * routine and reasonable tweaks to the TRUNC_* and
  87. * PIVOT_THRESHOLD values, you modify the _ID string so as
  88. * to make it clear that you have changed the code.
  89. *
  90. * If you find problems with this code, or find ways of
  91. * making it significantly faster, please let me know!
  92. * My e-mail address, valid as of early 2016 and for the
  93. * foreseeable future, is
  94. * gareth.mccaughan@pobox.com
  95. * Thanks!
  96. *
  97. * Gareth McCaughan
  98. */
  99. /* Copyright (c) 1998-2016 Gareth McCaughan
  100. *
  101. * This software is provided 'as-is', without any express or implied
  102. * warranty. In no event will the authors be held liable for any
  103. * damages arising from the use of this software.
  104. *
  105. * Permission is granted to anyone to use this software for any purpose,
  106. * including commercial applications, and to alter it and redistribute it
  107. * freely, subject to the following restrictions:
  108. *
  109. * 1. The origin of this software must not be misrepresented;
  110. * you must not claim that you wrote the original software.
  111. * If you use this software in a product, an acknowledgment
  112. * in the product documentation would be appreciated but
  113. * is not required.
  114. *
  115. * 2. Altered source versions must be plainly marked as such,
  116. * and must not be misrepresented as being the original software.
  117. *
  118. * 3. This notice may not be removed or altered from any source
  119. * distribution.
  120. */
  121. /* Revision history since release:
  122. * 1998-03-19 v1.12 First release I have any records of.
  123. * 2007-09-02 v1.13 Fix bug kindly reported by Dan Bodoh
  124. * (premature termination of recursion).
  125. * Add a few clarifying comments.
  126. * Minor improvements to debug output.
  127. * 2016-02-21 v1.14 Replace licence with 2-clause BSD,
  128. * and clarify a couple of things in
  129. * comments. No code changes.
  130. */
  131. /* BEGIN SDL CHANGE ... commented this out with an #if 0 block. --ryan. */
  132. #if 0
  133. #include <assert.h>
  134. #include <stdlib.h>
  135. #include <string.h>
  136. #define DEBUG_QSORT
  137. static char _ID[]="<qsort.c gjm 1.14 2016-02-21>";
  138. #endif
  139. /* END SDL CHANGE ... commented this out with an #if 0 block. --ryan. */
  140. /* How many bytes are there per word? (Must be a power of 2,
  141. * and must in fact equal sizeof(int).)
  142. */
  143. #define WORD_BYTES sizeof(int)
  144. /* How big does our stack need to be? Answer: one entry per
  145. * bit in a |size_t|.
  146. */
  147. #define STACK_SIZE (8*sizeof(size_t))
  148. /* Different situations have slightly different requirements,
  149. * and we make life epsilon easier by using different truncation
  150. * points for the three different cases.
  151. * So far, I have tuned TRUNC_words and guessed that the same
  152. * value might work well for the other two cases. Of course
  153. * what works well on my machine might work badly on yours.
  154. */
  155. #define TRUNC_nonaligned 12
  156. #define TRUNC_aligned 12
  157. #define TRUNC_words 12*WORD_BYTES /* nb different meaning */
  158. /* We use a simple pivoting algorithm for shortish sub-arrays
  159. * and a more complicated one for larger ones. The threshold
  160. * is PIVOT_THRESHOLD.
  161. */
  162. #define PIVOT_THRESHOLD 40
  163. typedef struct { char * first; char * last; } stack_entry;
  164. #define pushLeft {stack[stacktop].first=ffirst;stack[stacktop++].last=last;}
  165. #define pushRight {stack[stacktop].first=first;stack[stacktop++].last=llast;}
  166. #define doLeft {first=ffirst;llast=last;continue;}
  167. #define doRight {ffirst=first;last=llast;continue;}
  168. #define pop {if (--stacktop<0) break;\
  169. first=ffirst=stack[stacktop].first;\
  170. last=llast=stack[stacktop].last;\
  171. continue;}
  172. /* Some comments on the implementation.
  173. * 1. When we finish partitioning the array into "low"
  174. * and "high", we forget entirely about short subarrays,
  175. * because they'll be done later by insertion sort.
  176. * Doing lots of little insertion sorts might be a win
  177. * on large datasets for locality-of-reference reasons,
  178. * but it makes the code much nastier and increases
  179. * bookkeeping overhead.
  180. * 2. We always save the shorter and get to work on the
  181. * longer. This guarantees that every time we push
  182. * an item onto the stack its size is <= 1/2 of that
  183. * of its parent; so the stack can't need more than
  184. * log_2(max-array-size) entries.
  185. * 3. We choose a pivot by looking at the first, last
  186. * and middle elements. We arrange them into order
  187. * because it's easy to do that in conjunction with
  188. * choosing the pivot, and it makes things a little
  189. * easier in the partitioning step. Anyway, the pivot
  190. * is the middle of these three. It's still possible
  191. * to construct datasets where the algorithm takes
  192. * time of order n^2, but it simply never happens in
  193. * practice.
  194. * 3' Newsflash: On further investigation I find that
  195. * it's easy to construct datasets where median-of-3
  196. * simply isn't good enough. So on large-ish subarrays
  197. * we do a more sophisticated pivoting: we take three
  198. * sets of 3 elements, find their medians, and then
  199. * take the median of those.
  200. * 4. We copy the pivot element to a separate place
  201. * because that way we can always do our comparisons
  202. * directly against a pointer to that separate place,
  203. * and don't have to wonder "did we move the pivot
  204. * element?". This makes the inner loop better.
  205. * 5. It's possible to make the pivoting even more
  206. * reliable by looking at more candidates when n
  207. * is larger. (Taking this to its logical conclusion
  208. * results in a variant of quicksort that doesn't
  209. * have that n^2 worst case.) However, the overhead
  210. * from the extra bookkeeping means that it's just
  211. * not worth while.
  212. * 6. This is pretty clean and portable code. Here are
  213. * all the potential portability pitfalls and problems
  214. * I know of:
  215. * - In one place (the insertion sort) I construct
  216. * a pointer that points just past the end of the
  217. * supplied array, and assume that (a) it won't
  218. * compare equal to any pointer within the array,
  219. * and (b) it will compare equal to a pointer
  220. * obtained by stepping off the end of the array.
  221. * These might fail on some segmented architectures.
  222. * - I assume that there are 8 bits in a |char| when
  223. * computing the size of stack needed. This would
  224. * fail on machines with 9-bit or 16-bit bytes.
  225. * - I assume that if |((int)base&(sizeof(int)-1))==0|
  226. * and |(size&(sizeof(int)-1))==0| then it's safe to
  227. * get at array elements via |int*|s, and that if
  228. * actually |size==sizeof(int)| as well then it's
  229. * safe to treat the elements as |int|s. This might
  230. * fail on systems that convert pointers to integers
  231. * in non-standard ways.
  232. * - I assume that |8*sizeof(size_t)<=INT_MAX|. This
  233. * would be false on a machine with 8-bit |char|s,
  234. * 16-bit |int|s and 4096-bit |size_t|s. :-)
  235. */
  236. /* The recursion logic is the same in each case.
  237. * We keep chopping up until we reach subarrays of size
  238. * strictly less than Trunc; we leave these unsorted. */
  239. #define Recurse(Trunc) \
  240. { size_t l=last-ffirst,r=llast-first; \
  241. if (l<Trunc) { \
  242. if (r>=Trunc) doRight \
  243. else pop \
  244. } \
  245. else if (l<=r) { pushLeft; doRight } \
  246. else if (r>=Trunc) { pushRight; doLeft }\
  247. else doLeft \
  248. }
  249. /* and so is the pivoting logic (note: last is inclusive): */
  250. #define Pivot(swapper,sz) \
  251. if (last-first>PIVOT_THRESHOLD*sz) mid=pivot_big(first,mid,last,sz,compare);\
  252. else { \
  253. if (compare(first,mid)<0) { \
  254. if (compare(mid,last)>0) { \
  255. swapper(mid,last); \
  256. if (compare(first,mid)>0) swapper(first,mid);\
  257. } \
  258. } \
  259. else { \
  260. if (compare(mid,last)>0) swapper(first,last)\
  261. else { \
  262. swapper(first,mid); \
  263. if (compare(mid,last)>0) swapper(mid,last);\
  264. } \
  265. } \
  266. first+=sz; last-=sz; \
  267. }
  268. #ifdef DEBUG_QSORT
  269. #include <stdio.h>
  270. #endif
  271. /* and so is the partitioning logic: */
  272. #define Partition(swapper,sz) { \
  273. do { \
  274. while (compare(first,pivot)<0) first+=sz; \
  275. while (compare(pivot,last)<0) last-=sz; \
  276. if (first<last) { \
  277. swapper(first,last); \
  278. first+=sz; last-=sz; } \
  279. else if (first==last) { first+=sz; last-=sz; break; }\
  280. } while (first<=last); \
  281. }
  282. /* and so is the pre-insertion-sort operation of putting
  283. * the smallest element into place as a sentinel.
  284. * Doing this makes the inner loop nicer. I got this
  285. * idea from the GNU implementation of qsort().
  286. * We find the smallest element from the first |nmemb|,
  287. * or the first |limit|, whichever is smaller;
  288. * therefore we must have ensured that the globally smallest
  289. * element is in the first |limit|.
  290. */
  291. #define PreInsertion(swapper,limit,sz) \
  292. first=base; \
  293. last=first + ((nmemb>limit ? limit : nmemb)-1)*sz;\
  294. while (last!=base) { \
  295. if (compare(first,last)>0) first=last; \
  296. last-=sz; } \
  297. if (first!=base) swapper(first,(char*)base);
  298. /* and so is the insertion sort, in the first two cases: */
  299. #define Insertion(swapper) \
  300. last=((char*)base)+nmemb*size; \
  301. for (first=((char*)base)+size;first!=last;first+=size) { \
  302. char *test; \
  303. /* Find the right place for |first|. \
  304. * My apologies for var reuse. */ \
  305. for (test=first-size;compare(test,first)>0;test-=size) ; \
  306. test+=size; \
  307. if (test!=first) { \
  308. /* Shift everything in [test,first) \
  309. * up by one, and place |first| \
  310. * where |test| is. */ \
  311. memcpy(pivot,first,size); \
  312. memmove(test+size,test,first-test); \
  313. memcpy(test,pivot,size); \
  314. } \
  315. }
  316. #define SWAP_nonaligned(a,b) { \
  317. register char *aa=(a),*bb=(b); \
  318. register size_t sz=size; \
  319. do { register char t=*aa; *aa++=*bb; *bb++=t; } while (--sz); }
  320. #define SWAP_aligned(a,b) { \
  321. register int *aa=(int*)(a),*bb=(int*)(b); \
  322. register size_t sz=size; \
  323. do { register int t=*aa;*aa++=*bb; *bb++=t; } while (sz-=WORD_BYTES); }
  324. #define SWAP_words(a,b) { \
  325. register int t=*((int*)a); *((int*)a)=*((int*)b); *((int*)b)=t; }
  326. /* ---------------------------------------------------------------------- */
  327. static char * pivot_big(char *first, char *mid, char *last, size_t size,
  328. int compare(const void *, const void *)) {
  329. int d=(((last-first)/size)>>3)*size;
  330. #ifdef DEBUG_QSORT
  331. fprintf(stderr, "pivot_big: first=%p last=%p size=%lu n=%lu\n", first, (unsigned long)last, size, (unsigned long)((last-first+1)/size));
  332. #endif
  333. char *m1,*m2,*m3;
  334. { char *a=first, *b=first+d, *c=first+2*d;
  335. #ifdef DEBUG_QSORT
  336. fprintf(stderr,"< %d %d %d @ %p %p %p\n",*(int*)a,*(int*)b,*(int*)c, a,b,c);
  337. #endif
  338. m1 = compare(a,b)<0 ?
  339. (compare(b,c)<0 ? b : (compare(a,c)<0 ? c : a))
  340. : (compare(a,c)<0 ? a : (compare(b,c)<0 ? c : b));
  341. }
  342. { char *a=mid-d, *b=mid, *c=mid+d;
  343. #ifdef DEBUG_QSORT
  344. fprintf(stderr,". %d %d %d @ %p %p %p\n",*(int*)a,*(int*)b,*(int*)c, a,b,c);
  345. #endif
  346. m2 = compare(a,b)<0 ?
  347. (compare(b,c)<0 ? b : (compare(a,c)<0 ? c : a))
  348. : (compare(a,c)<0 ? a : (compare(b,c)<0 ? c : b));
  349. }
  350. { char *a=last-2*d, *b=last-d, *c=last;
  351. #ifdef DEBUG_QSORT
  352. fprintf(stderr,"> %d %d %d @ %p %p %p\n",*(int*)a,*(int*)b,*(int*)c, a,b,c);
  353. #endif
  354. m3 = compare(a,b)<0 ?
  355. (compare(b,c)<0 ? b : (compare(a,c)<0 ? c : a))
  356. : (compare(a,c)<0 ? a : (compare(b,c)<0 ? c : b));
  357. }
  358. #ifdef DEBUG_QSORT
  359. fprintf(stderr,"-> %d %d %d @ %p %p %p\n",*(int*)m1,*(int*)m2,*(int*)m3, m1,m2,m3);
  360. #endif
  361. return compare(m1,m2)<0 ?
  362. (compare(m2,m3)<0 ? m2 : (compare(m1,m3)<0 ? m3 : m1))
  363. : (compare(m1,m3)<0 ? m1 : (compare(m2,m3)<0 ? m3 : m2));
  364. }
  365. /* ---------------------------------------------------------------------- */
  366. static void qsort_nonaligned(void *base, size_t nmemb, size_t size,
  367. int (*compare)(const void *, const void *)) {
  368. stack_entry stack[STACK_SIZE];
  369. int stacktop=0;
  370. char *first,*last;
  371. char *pivot=malloc(size);
  372. size_t trunc=TRUNC_nonaligned*size;
  373. assert(pivot!=0);
  374. first=(char*)base; last=first+(nmemb-1)*size;
  375. if (last-first>=trunc) {
  376. char *ffirst=first, *llast=last;
  377. while (1) {
  378. /* Select pivot */
  379. { char * mid=first+size*((last-first)/size >> 1);
  380. Pivot(SWAP_nonaligned,size);
  381. memcpy(pivot,mid,size);
  382. }
  383. /* Partition. */
  384. Partition(SWAP_nonaligned,size);
  385. /* Prepare to recurse/iterate. */
  386. Recurse(trunc)
  387. }
  388. }
  389. PreInsertion(SWAP_nonaligned,TRUNC_nonaligned-1,size);
  390. Insertion(SWAP_nonaligned);
  391. free(pivot);
  392. }
  393. static void qsort_aligned(void *base, size_t nmemb, size_t size,
  394. int (*compare)(const void *, const void *)) {
  395. stack_entry stack[STACK_SIZE];
  396. int stacktop=0;
  397. char *first,*last;
  398. char *pivot=malloc(size);
  399. size_t trunc=TRUNC_aligned*size;
  400. assert(pivot!=0);
  401. first=(char*)base; last=first+(nmemb-1)*size;
  402. if (last-first>=trunc) {
  403. char *ffirst=first,*llast=last;
  404. while (1) {
  405. /* Select pivot */
  406. { char * mid=first+size*((last-first)/size >> 1);
  407. Pivot(SWAP_aligned,size);
  408. memcpy(pivot,mid,size);
  409. }
  410. /* Partition. */
  411. Partition(SWAP_aligned,size);
  412. /* Prepare to recurse/iterate. */
  413. Recurse(trunc)
  414. }
  415. }
  416. PreInsertion(SWAP_aligned,TRUNC_aligned-1,size);
  417. Insertion(SWAP_aligned);
  418. free(pivot);
  419. }
  420. static void qsort_words(void *base, size_t nmemb,
  421. int (*compare)(const void *, const void *)) {
  422. stack_entry stack[STACK_SIZE];
  423. int stacktop=0;
  424. char *first,*last;
  425. char *pivot=malloc(WORD_BYTES);
  426. assert(pivot!=0);
  427. first=(char*)base; last=first+(nmemb-1)*WORD_BYTES;
  428. if (last-first>=TRUNC_words) {
  429. char *ffirst=first, *llast=last;
  430. while (1) {
  431. #ifdef DEBUG_QSORT
  432. fprintf(stderr,"Doing %d:%d: ",
  433. (first-(char*)base)/WORD_BYTES,
  434. (last-(char*)base)/WORD_BYTES);
  435. #endif
  436. /* Select pivot */
  437. { char * mid=first+WORD_BYTES*((last-first) / (2*WORD_BYTES));
  438. Pivot(SWAP_words,WORD_BYTES);
  439. *(int*)pivot=*(int*)mid;
  440. #ifdef DEBUG_QSORT
  441. fprintf(stderr,"pivot = %p = #%lu = %d\n", mid, (unsigned long)(((int*)mid)-((int*)base)), *(int*)mid);
  442. #endif
  443. }
  444. /* Partition. */
  445. Partition(SWAP_words,WORD_BYTES);
  446. #ifdef DEBUG_QSORT
  447. fprintf(stderr, "after partitioning first=#%lu last=#%lu\n", (first-(char*)base)/4lu, (last-(char*)base)/4lu);
  448. #endif
  449. /* Prepare to recurse/iterate. */
  450. Recurse(TRUNC_words)
  451. }
  452. }
  453. PreInsertion(SWAP_words,(TRUNC_words/WORD_BYTES)-1,WORD_BYTES);
  454. /* Now do insertion sort. */
  455. last=((char*)base)+nmemb*WORD_BYTES;
  456. for (first=((char*)base)+WORD_BYTES;first!=last;first+=WORD_BYTES) {
  457. /* Find the right place for |first|. My apologies for var reuse */
  458. int *pl=(int*)(first-WORD_BYTES),*pr=(int*)first;
  459. *(int*)pivot=*(int*)first;
  460. for (;compare(pl,pivot)>0;pr=pl,--pl) {
  461. *pr=*pl; }
  462. if (pr!=(int*)first) *pr=*(int*)pivot;
  463. }
  464. free(pivot);
  465. }
  466. /* ---------------------------------------------------------------------- */
  467. extern void qsortG(void *base, size_t nmemb, size_t size,
  468. int (*compare)(const void *, const void *)) {
  469. if (nmemb<=1) return;
  470. if (((int)base|size)&(WORD_BYTES-1))
  471. qsort_nonaligned(base,nmemb,size,compare);
  472. else if (size!=WORD_BYTES)
  473. qsort_aligned(base,nmemb,size,compare);
  474. else
  475. qsort_words(base,nmemb,compare);
  476. }
  477. #endif /* HAVE_QSORT */
  478. /* vi: set ts=4 sw=4 expandtab: */