enum { /** * "from Knuth" * * A binary search over 8 items performs 4 comparisons: * log2(8)=3 to subdivide, +1 to check for equality. * A linear search over 8 items on average also performs 4 comparisons.
*/
MIN_QSORT=9,
STACK_ITEM_SIZE=200
};
/* Binary search until we get down to a tiny sub-array. */ while((limit-start)>=MIN_QSORT) {
int32_t i=(start+limit)/2;
int32_t diff=cmp(context, item, array+i*itemSize); if(diff==0) { /* * Found the item. We look for the *last* occurrence of such * an item, for stable sorting. * If we knew that there will be only few equal items, * we could break now and enter the linear search. * However, if there are many equal items, then it should be * faster to continue with the binary search. * It seems likely that we either have all unique items * (where found will never become true in the insertion sort) * or potentially many duplicates.
*/
found=true;
start=i+1;
} elseif(diff<0) {
limit=i;
} else {
start=i;
}
}
/* Linear search over the remaining tiny sub-array. */ while(start<limit) {
int32_t diff=cmp(context, item, array+start*itemSize); if(diff==0) {
found=true;
} elseif(diff<0) { break;
}
++start;
} return found ? (start-1) : ~start;
}
/* * This implementation is semi-recursive: * It recurses for the smaller sub-array to shorten the recursion depth, * and loops for the larger sub-array. * * Loosely after QuickSort algorithms in * Niklaus Wirth * Algorithmen und Datenstrukturen mit Modula-2 * B.G. Teubner Stuttgart * 4. Auflage 1986 * ISBN 3-519-02260-5
*/ staticvoid
subQuickSort(char *array, int32_t start, int32_t limit, int32_t itemSize,
UComparator *cmp, constvoid *context, void *px, void *pw) {
int32_t left, right;
/* start and left are inclusive, limit and right are exclusive */ do { if((start+MIN_QSORT)>=limit) {
doInsertionSort(array+start*itemSize, limit-start, itemSize, cmp, context, px); break;
}
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.