24 #define SWAP(a, b) { int c = *(a); *(a) = *(b); *(b) = c; }
28 template<
typename intType>
36 #define STACK_SIZE (CHAR_BIT * sizeof(size_t))
37 #define PUSH(low, high) ((void) ((top->lo = (low)), (top->hi = (high)), ++top))
38 #define POP(low, high) ((void) (--top, (low = top->lo), (high = top->hi)))
39 #define STACK_NOT_EMPTY (stack < top)
41 #define min(x, y) ((x) < (y) ? (x) : (y))
43 template<
typename intType>
44 void qsort_int(intType* pbase,
size_t total_elems)
46 register intType *base_ptr = pbase;
48 if (total_elems == 0)
return;
50 if (total_elems > MAX_THRESH)
52 intType *lo = base_ptr;
53 intType *hi = lo + total_elems - 1;
57 PUSH(
nullptr,
nullptr);
59 while (STACK_NOT_EMPTY)
70 intType *mid = lo + ((hi - lo) >> 1);
90 while (*left_ptr < *mid)
93 while (*mid < *right_ptr)
96 if (left_ptr < right_ptr)
98 SWAP(left_ptr, right_ptr);
101 else if (mid == right_ptr)
106 else if (left_ptr == right_ptr)
112 }
while (left_ptr <= right_ptr);
119 if ((
size_t)(right_ptr - lo) <= MAX_THRESH)
121 if ((
size_t)(hi - left_ptr) <= MAX_THRESH)
128 else if ((
size_t)(hi - left_ptr) <= MAX_THRESH)
131 else if ((right_ptr - lo) > (hi - left_ptr))
152 intType *
const end_ptr = base_ptr + total_elems - 1;
153 intType *tmp_ptr = base_ptr;
154 intType *thresh = min(end_ptr, base_ptr + MAX_THRESH);
155 register intType *run_ptr;
161 for (run_ptr = tmp_ptr + 1; run_ptr <= thresh; run_ptr++)
162 if (*run_ptr < *tmp_ptr)
165 if (tmp_ptr != base_ptr)
166 SWAP(tmp_ptr, base_ptr);
169 run_ptr = base_ptr + 1;
170 while (++run_ptr <= end_ptr)
172 tmp_ptr = run_ptr - 1;
173 while (*run_ptr < *tmp_ptr)
177 if (tmp_ptr != run_ptr)
179 intType c = *run_ptr;
180 register intType *hi, *lo;
182 for (hi = lo = run_ptr; --lo >= tmp_ptr; hi = lo)
190 template void qsort_int(
int* pbase,
size_t total_elems);
The QuickSort routine from glibc-2.5 modified for sorting int arrays.