SDL_qsort.c 18 KB

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