Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define stb_declare_sort(FUNCNAME, TYPE) \
- void FUNCNAME(TYPE *p, int n)
- #define stb_define_sort(FUNCNAME,TYPE,COMPARE) \
- stb__define_sort( void, FUNCNAME,TYPE,COMPARE)
- #define stb_define_sort_static(FUNCNAME,TYPE,COMPARE) \
- stb__define_sort(static void, FUNCNAME,TYPE,COMPARE)
- #define stb__define_sort(MODE, FUNCNAME, TYPE, COMPARE) \
- \
- static void STB_(FUNCNAME,_ins_sort)(TYPE *p, int n) \
- { \
- int i,j; \
- for (i=1; i < n; ++i) { \
- TYPE t = p[i], *a = &t; \
- j = i; \
- while (j > 0) { \
- TYPE *b = &p[j-1]; \
- int c = COMPARE; \
- if (!c) break; \
- p[j] = p[j-1]; \
- --j; \
- } \
- if (i != j) \
- p[j] = t; \
- } \
- } \
- \
- static void STB_(FUNCNAME,_quicksort)(TYPE *p, int n) \
- { \
- /* threshhold for transitioning to insertion sort */ \
- while (n > 12) { \
- TYPE *a,*b,t; \
- int c01,c12,c,m,i,j; \
- \
- /* compute median of three */ \
- m = n >> 1; \
- a = &p[0]; \
- b = &p[m]; \
- c = COMPARE; \
- c01 = c; \
- a = &p[m]; \
- b = &p[n-1]; \
- c = COMPARE; \
- c12 = c; \
- /* if 0 >= mid >= end, or 0 < mid < end, then use mid */ \
- if (c01 != c12) { \
- /* otherwise, we'll need to swap something else to middle */ \
- int z; \
- a = &p[0]; \
- b = &p[n-1]; \
- c = COMPARE; \
- /* 0>mid && mid<n: 0>n => n; 0<n => 0 */ \
- /* 0<mid && mid>n: 0>n => 0; 0<n => n */ \
- z = (c == c12) ? 0 : n-1; \
- t = p[z]; \
- p[z] = p[m]; \
- p[m] = t; \
- } \
- /* now p[m] is the median-of-three */ \
- /* swap it to the beginning so it won't move around */ \
- t = p[0]; \
- p[0] = p[m]; \
- p[m] = t; \
- \
- /* partition loop */ \
- i=1; \
- j=n-1; \
- for(;;) { \
- /* handling of equality is crucial here */ \
- /* for sentinels & efficiency with duplicates */ \
- b = &p[0]; \
- for (;;++i) { \
- a=&p[i]; \
- c = COMPARE; \
- if (!c) break; \
- } \
- a = &p[0]; \
- for (;;--j) { \
- b=&p[j]; \
- c = COMPARE; \
- if (!c) break; \
- } \
- /* make sure we haven't crossed */ \
- if (i >= j) break; \
- t = p[i]; \
- p[i] = p[j]; \
- p[j] = t; \
- \
- ++i; \
- --j; \
- } \
- /* recurse on smaller side, iterate on larger */ \
- if (j < (n-i)) { \
- STB_(FUNCNAME,_quicksort)(p,j); \
- p = p+i; \
- n = n-i; \
- } else { \
- STB_(FUNCNAME,_quicksort)(p+i, n-i); \
- n = j; \
- } \
- } \
- } \
- \
- MODE FUNCNAME(TYPE *p, int n) \
- { \
- STB_(FUNCNAME, _quicksort)(p, n); \
- STB_(FUNCNAME, _ins_sort)(p, n); \
- }
Add Comment
Please, Sign In to add comment