SDL_qsort.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  1. /*
  2. Simple DirectMedia Layer
  3. Copyright (C) 1997-2023 Sam Lantinga <[email protected]>
  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. #include "SDL_internal.h"
  19. #ifdef HAVE_QSORT
  20. void SDL_qsort(void *base, size_t nmemb, size_t size, int (*compare) (const void *, const void *))
  21. {
  22. qsort(base, nmemb, size, compare);
  23. }
  24. #else
  25. #ifdef assert
  26. #undef assert
  27. #endif
  28. #define assert SDL_assert
  29. #ifdef malloc
  30. #undef malloc
  31. #endif
  32. #define malloc SDL_malloc
  33. #ifdef free
  34. #undef free
  35. #endif
  36. #define free SDL_free
  37. #ifdef memcpy
  38. #undef memcpy
  39. #endif
  40. #define memcpy SDL_memcpy
  41. #ifdef memmove
  42. #undef memmove
  43. #endif
  44. #define memmove SDL_memmove
  45. #ifdef qsortG
  46. #undef qsortG
  47. #endif
  48. #define qsortG SDL_qsort
  49. /*
  50. This code came from Gareth McCaughan, under the zlib license.
  51. Specifically this: https://www.mccaughan.org.uk/software/qsort.c-1.15
  52. Everything below this comment until the HAVE_QSORT #endif was from Gareth
  53. (any minor changes will be noted inline).
  54. Thank you to Gareth for relicensing this code under the zlib license for our
  55. benefit!
  56. --ryan.
  57. */
  58. /* This is a drop-in replacement for the C library's |qsort()| routine.
  59. *
  60. * It is intended for use where you know or suspect that your
  61. * platform's qsort is bad. If that isn't the case, then you
  62. * should probably use the qsort your system gives you in preference
  63. * to mine -- it will likely have been tested and tuned better.
  64. *
  65. * Features:
  66. * - Median-of-three pivoting (and more)
  67. * - Truncation and final polishing by a single insertion sort
  68. * - Early truncation when no swaps needed in pivoting step
  69. * - Explicit recursion, guaranteed not to overflow
  70. * - A few little wrinkles stolen from the GNU |qsort()|.
  71. * (For the avoidance of doubt, no code was stolen, only
  72. * broad ideas.)
  73. * - separate code for non-aligned / aligned / word-size objects
  74. *
  75. * Earlier releases of this code used an idiosyncratic licence
  76. * I wrote myself, because I'm an idiot. The code is now released
  77. * under the "zlib/libpng licence"; you will find the actual
  78. * terms in the next comment. I request (but do not require)
  79. * that if you make any changes beyond the name of the exported
  80. * routine and reasonable tweaks to the TRUNC_* and
  81. * PIVOT_THRESHOLD values, you modify the _ID string so as
  82. * to make it clear that you have changed the code.
  83. *
  84. * If you find problems with this code, or find ways of
  85. * making it significantly faster, please let me know!
  86. * My e-mail address, valid as of early 2016 and for the
  87. * foreseeable future, is
  88. * [email protected]
  89. * Thanks!
  90. *
  91. * Gareth McCaughan
  92. */
  93. /* Copyright (c) 1998-2016 Gareth McCaughan
  94. *
  95. * This software is provided 'as-is', without any express or implied
  96. * warranty. In no event will the authors be held liable for any
  97. * damages arising from the use of this software.
  98. *
  99. * Permission is granted to anyone to use this software for any purpose,
  100. * including commercial applications, and to alter it and redistribute it
  101. * freely, subject to the following restrictions:
  102. *
  103. * 1. The origin of this software must not be misrepresented;
  104. * you must not claim that you wrote the original software.
  105. * If you use this software in a product, an acknowledgment
  106. * in the product documentation would be appreciated but
  107. * is not required.
  108. *
  109. * 2. Altered source versions must be plainly marked as such,
  110. * and must not be misrepresented as being the original software.
  111. *
  112. * 3. This notice may not be removed or altered from any source
  113. * distribution.
  114. */
  115. /* Revision history since release:
  116. * 1998-03-19 v1.12 First release I have any records of.
  117. * 2007-09-02 v1.13 Fix bug kindly reported by Dan Bodoh
  118. * (premature termination of recursion).
  119. * Add a few clarifying comments.
  120. * Minor improvements to debug output.
  121. * 2016-02-21 v1.14 Replace licence with 2-clause BSD,
  122. * and clarify a couple of things in
  123. * comments. No code changes.
  124. * 2016-03-10 v1.15 Fix bug kindly reported by Ryan Gordon
  125. * (pre-insertion-sort messed up).
  126. * Disable DEBUG_QSORT by default.
  127. * Tweak comments very slightly.
  128. */
  129. /* BEGIN SDL CHANGE ... commented this out with an #if 0 block. --ryan. */
  130. #if 0
  131. #include <assert.h>
  132. #include <stdlib.h>
  133. #include <string.h>
  134. #undef DEBUG_QSORT
  135. static char _ID[]="<qsort.c gjm 1.15 2016-03-10>";
  136. #endif
  137. /* END SDL CHANGE ... commented this out with an #if 0 block. --ryan. */
  138. /* How many bytes are there per word? (Must be a power of 2,
  139. * and must in fact equal sizeof(int).)
  140. */
  141. #define WORD_BYTES sizeof(int)
  142. /* How big does our stack need to be? Answer: one entry per
  143. * bit in a |size_t|.
  144. */
  145. #define STACK_SIZE (8*sizeof(size_t))
  146. /* Different situations have slightly different requirements,
  147. * and we make life epsilon easier by using different truncation
  148. * points for the three different cases.
  149. * So far, I have tuned TRUNC_words and guessed that the same
  150. * value might work well for the other two cases. Of course
  151. * what works well on my machine might work badly on yours.
  152. */
  153. #define TRUNC_nonaligned 12
  154. #define TRUNC_aligned 12
  155. #define TRUNC_words 12*WORD_BYTES /* nb different meaning */
  156. /* We use a simple pivoting algorithm for shortish sub-arrays
  157. * and a more complicated one for larger ones. The threshold
  158. * is PIVOT_THRESHOLD.
  159. */
  160. #define PIVOT_THRESHOLD 40
  161. typedef struct { char * first; char * last; } stack_entry;
  162. #define pushLeft {stack[stacktop].first=ffirst;stack[stacktop++].last=last;}
  163. #define pushRight {stack[stacktop].first=first;stack[stacktop++].last=llast;}
  164. #define doLeft {first=ffirst;llast=last;continue;}
  165. #define doRight {ffirst=first;last=llast;continue;}
  166. #define pop {if (--stacktop<0) break;\
  167. first=ffirst=stack[stacktop].first;\
  168. last=llast=stack[stacktop].last;\
  169. continue;}
  170. /* Some comments on the implementation.
  171. * 1. When we finish partitioning the array into "low"
  172. * and "high", we forget entirely about short subarrays,
  173. * because they'll be done later by insertion sort.
  174. * Doing lots of little insertion sorts might be a win
  175. * on large datasets for locality-of-reference reasons,
  176. * but it makes the code much nastier and increases
  177. * bookkeeping overhead.
  178. * 2. We always save the shorter and get to work on the
  179. * longer. This guarantees that every time we push
  180. * an item onto the stack its size is <= 1/2 of that
  181. * of its parent; so the stack can't need more than
  182. * log_2(max-array-size) entries.
  183. * 3. We choose a pivot by looking at the first, last
  184. * and middle elements. We arrange them into order
  185. * because it's easy to do that in conjunction with
  186. * choosing the pivot, and it makes things a little
  187. * easier in the partitioning step. Anyway, the pivot
  188. * is the middle of these three. It's still possible
  189. * to construct datasets where the algorithm takes
  190. * time of order n^2, but it simply never happens in
  191. * practice.
  192. * 3' Newsflash: On further investigation I find that
  193. * it's easy to construct datasets where median-of-3
  194. * simply isn't good enough. So on large-ish subarrays
  195. * we do a more sophisticated pivoting: we take three
  196. * sets of 3 elements, find their medians, and then
  197. * take the median of those.
  198. * 4. We copy the pivot element to a separate place
  199. * because that way we can always do our comparisons
  200. * directly against a pointer to that separate place,
  201. * and don't have to wonder "did we move the pivot
  202. * element?". This makes the inner loop better.
  203. * 5. It's possible to make the pivoting even more
  204. * reliable by looking at more candidates when n
  205. * is larger. (Taking this to its logical conclusion
  206. * results in a variant of quicksort that doesn't
  207. * have that n^2 worst case.) However, the overhead
  208. * from the extra bookkeeping means that it's just
  209. * not worth while.
  210. * 6. This is pretty clean and portable code. Here are
  211. * all the potential portability pitfalls and problems
  212. * I know of:
  213. * - In one place (the insertion sort) I construct
  214. * a pointer that points just past the end of the
  215. * supplied array, and assume that (a) it won't
  216. * compare equal to any pointer within the array,
  217. * and (b) it will compare equal to a pointer
  218. * obtained by stepping off the end of the array.
  219. * These might fail on some segmented architectures.
  220. * - I assume that there are 8 bits in a |char| when
  221. * computing the size of stack needed. This would
  222. * fail on machines with 9-bit or 16-bit bytes.
  223. * - I assume that if |((int)base&(sizeof(int)-1))==0|
  224. * and |(size&(sizeof(int)-1))==0| then it's safe to
  225. * get at array elements via |int*|s, and that if
  226. * actually |size==sizeof(int)| as well then it's
  227. * safe to treat the elements as |int|s. This might
  228. * fail on systems that convert pointers to integers
  229. * in non-standard ways.
  230. * - I assume that |8*sizeof(size_t)<=INT_MAX|. This
  231. * would be false on a machine with 8-bit |char|s,
  232. * 16-bit |int|s and 4096-bit |size_t|s. :-)
  233. */
  234. /* The recursion logic is the same in each case.
  235. * We keep chopping up until we reach subarrays of size
  236. * strictly less than Trunc; we leave these unsorted. */
  237. #define Recurse(Trunc) \
  238. { size_t l=last-ffirst,r=llast-first; \
  239. if (l<Trunc) { \
  240. if (r>=Trunc) doRight \
  241. else pop \
  242. } \
  243. else if (l<=r) { pushLeft; doRight } \
  244. else if (r>=Trunc) { pushRight; doLeft }\
  245. else doLeft \
  246. }
  247. /* and so is the pivoting logic (note: last is inclusive): */
  248. #define Pivot(swapper,sz) \
  249. if ((size_t)(last-first)>PIVOT_THRESHOLD*sz) mid=pivot_big(first,mid,last,sz,compare);\
  250. else { \
  251. if (compare(first,mid)<0) { \
  252. if (compare(mid,last)>0) { \
  253. swapper(mid,last); \
  254. if (compare(first,mid)>0) swapper(first,mid);\
  255. } \
  256. } \
  257. else { \
  258. if (compare(mid,last)>0) swapper(first,last)\
  259. else { \
  260. swapper(first,mid); \
  261. if (compare(mid,last)>0) swapper(mid,last);\
  262. } \
  263. } \
  264. first+=sz; last-=sz; \
  265. }
  266. #ifdef DEBUG_QSORT
  267. #include <stdio.h>
  268. #endif
  269. /* and so is the partitioning logic: */
  270. #define Partition(swapper,sz) { \
  271. do { \
  272. while (compare(first,pivot)<0) first+=sz; \
  273. while (compare(pivot,last)<0) last-=sz; \
  274. if (first<last) { \
  275. swapper(first,last); \
  276. first+=sz; last-=sz; } \
  277. else if (first==last) { first+=sz; last-=sz; break; }\
  278. } while (first<=last); \
  279. }
  280. /* and so is the pre-insertion-sort operation of putting
  281. * the smallest element into place as a sentinel.
  282. * Doing this makes the inner loop nicer. I got this
  283. * idea from the GNU implementation of qsort().
  284. * We find the smallest element from the first |nmemb|,
  285. * or the first |limit|, whichever is smaller;
  286. * therefore we must have ensured that the globally smallest
  287. * element is in the first |limit| (because our
  288. * quicksort recursion bottoms out only once we
  289. * reach subarrays smaller than |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. size_t 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 != NULL);
  374. first=(char*)base; last=first+(nmemb-1)*size;
  375. if ((size_t)(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,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 != NULL);
  401. first=(char*)base; last=first+(nmemb-1)*size;
  402. if ((size_t)(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,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 != NULL);
  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,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 (((size_t)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. void *SDL_bsearch(const void *key, const void *base, size_t nmemb, size_t size, int (*compare)(const void *, const void *))
  479. {
  480. #ifdef HAVE_BSEARCH
  481. return bsearch(key, base, nmemb, size, compare);
  482. #else
  483. /* SDL's replacement: Taken from the Public Domain C Library (PDCLib):
  484. Permission is granted to use, modify, and / or redistribute at will.
  485. */
  486. const void *pivot;
  487. size_t corr;
  488. int rc;
  489. while (nmemb) {
  490. /* algorithm needs -1 correction if remaining elements are an even number. */
  491. corr = nmemb % 2;
  492. nmemb /= 2;
  493. pivot = (const char *)base + (nmemb * size);
  494. rc = compare(key, pivot);
  495. if (rc > 0) {
  496. base = (const char *)pivot + size;
  497. /* applying correction */
  498. nmemb -= (1 - corr);
  499. } else if (rc == 0) {
  500. return (void *)pivot;
  501. }
  502. }
  503. return NULL;
  504. #endif /* HAVE_BSEARCH */
  505. }