SDL_qsort.c 19 KB

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