sorting - Looking for error in C++ Quicksort / Insertion sort combo -
im trying build quicksort / insertion sort combo, fast, tackles larger subarrays quicksort , smaller arrays insertion sort, not correct. i've been testing sorting files generated. i'm using file of 1,000,000 numbers, range limit on each number being 1 1,000,000. prior adding insertion sort, able sort 1 million numbers in 0.2 seconds, after adding insertion sort conditional if statement, i'm lucky sort 100,000 numbers in less 4 seconds, know there's error in code, can't find it. code amalgam of different online references these types of sorting methods, don't claim code own , can provide links original if necessary. however, references used weren't written in c++ , class-oriented, had make changes, why think there's error.
void modifiedquicksort(arrptr &arraypointer, int first, int last) { int firsttemp = first, lasttemp = last; int temp; int pivot = arraypointer[(first + last) / 2]; if((last - first) < 10) { insertionsort(arraypointer, last + 1); } else { // partitioning step while (firsttemp <= lasttemp) { while (arraypointer[firsttemp] < pivot) firsttemp++; while (arraypointer[lasttemp] > pivot) lasttemp--; if (firsttemp <= lasttemp) { temp = arraypointer[firsttemp]; arraypointer[firsttemp] = arraypointer[lasttemp]; arraypointer[lasttemp] = temp; firsttemp++; lasttemp--; } } // recursive step if (first < lasttemp) modifiedquicksort(arraypointer, first, lasttemp); if (firsttemp < last) modifiedquicksort(arraypointer, firsttemp, last); } } void insertionsort(arrptr &arraypointer, const int &arraysize) { int i, key, j; (i = 1; < arraysize; i++) { key = arraypointer[i]; j = i-1; /* move elements of arr[0..i-1], greater key, 1 position ahead of current position */ while (j >= 0 && arraypointer[j] > key) { arraypointer[j+1] = arraypointer[j]; j = j-1; } arraypointer[j+1] = key; } }
if inspect execution of insertion sort see gets sort far larger arrays size 10. have been caught, had followed excellent advice given in lipperts writeup linked πάντα ῥεῖ.
if you’ve still got bug first double check specifications contain preconditions , postconditions of every method.
and
if you’ve still got bug learn how write assertions verify preconditions , postconditions.
the function call
if((last - first) < 10) { insertionsort(arraypointer, last + 1); }
indicates insertionsort
operates on entire array [0, last]
not [first, last]
.
change , performance of modifiedquicksort
behave expected.
Comments
Post a Comment