26 #define SHELLSORTMAX 25 29 template <
class T,
class COMPARATOR >
30 void SPxShellsort(T* keys,
int end, COMPARATOR& compare,
int start = 0)
32 static const int incs[3] = {1, 5, 19};
37 for(k = 2; k >= 0; --k)
40 int first = h + start;
43 for(i = first; i <= end; ++i)
50 while(j >= first && compare(tempkey, keys[j - h]) < 0)
52 keys[j] = keys[j - h];
72 template <
class T,
class COMPARATOR >
73 void SPxQuicksort(T* keys,
int end, COMPARATOR& compare,
int start = 0,
bool type =
true)
94 mid = start + (end - start) / 2;
107 while(lo < end && compare(keys[lo], pivotkey) < 0)
110 while(hi > start && compare(keys[hi], pivotkey) >= 0)
115 while(lo < end && compare(keys[lo], pivotkey) <= 0)
118 while(hi > start && compare(keys[hi], pivotkey) > 0)
133 assert((hi == lo - 1) || (type && hi == start) || (!type && lo == end));
138 while(lo < end && compare(pivotkey, keys[lo]) >= 0)
145 assert(compare(keys[mid], pivotkey) == 0);
148 keys[lo] = keys[mid];
156 while(hi > start && compare(pivotkey, keys[hi]) <= 0)
163 assert(compare(keys[mid], pivotkey) == 0);
166 keys[hi] = keys[mid];
174 if(hi - start <= end - lo)
208 for(
int i = start; i < end; ++i)
209 assert(compare(keys[i], keys[i + 1]) <= 0);
236 template <
class T,
class COMPARATOR >
237 int SPxQuicksortPart(T* keys, COMPARATOR& compare,
int start,
int end,
int size,
int start2 = 0,
238 int end2 = 0,
bool type =
true)
245 else if(end == start + 1)
254 assert(start2 < end);
256 for(
int i = start; i < start2 - 1; ++i)
257 assert(compare(keys[i], keys[i + 1]) <= 0);
263 if(start2 + size >= end - 1)
279 mid = (start2 + end) / 2;
280 pivotkey = keys[mid];
290 while(lo < end && compare(keys[lo], pivotkey) < 0)
293 while(hi > start2 && compare(keys[hi], pivotkey) >= 0)
298 while(lo < end && compare(keys[lo], pivotkey) <= 0)
301 while(hi > start2 && compare(keys[hi], pivotkey) > 0)
316 assert((hi == lo - 1) || (type && hi == start2) || (!type && lo == end));
321 while(lo < end && compare(pivotkey, keys[lo]) >= 0)
328 assert(compare(keys[mid], pivotkey) == 0);
331 keys[lo] = keys[mid];
339 while(hi > start2 && compare(pivotkey, keys[hi]) <= 0)
346 assert(compare(keys[mid], pivotkey) == 0);
349 keys[hi] = keys[mid];
358 for(
int i = start2; i < lo; ++i)
359 assert(compare(keys[i], pivotkey) <= 0);
364 if(2 * size <= hi - start2)
366 return SPxQuicksortPart(keys, compare, start, hi + 1, size, start2, end2, !type);
369 else if(size <= lo - start2)
378 return SPxQuicksortPart(keys, compare, start, end + 1, size + start2 - lo, lo, end2, !type);
void SPxQuicksort(T *keys, int end, COMPARATOR &compare, int start=0, bool type=true)
Generic QuickSort implementation.
void SPxShellsort(T *keys, int end, COMPARATOR &compare, int start=0)
Everything should be within this namespace.
int SPxQuicksortPart(T *keys, COMPARATOR &compare, int start, int end, int size, int start2=0, int end2=0, bool type=true)
Generic implementation of Partial QuickSort.