For this sorting algorithm I wrote, I have two questions:
1.When I range fill a vector [max-num, 0]
(worst-case scenario) I get a result way better than O(n^2)
. (I'm not even sure if I even wrote a quicksort anymore).
2.When I mix up the range, ex: I fill the unsorted vector [0, max-num/2]
then [max-num/2, 0]
, weirdly enough it runs with crashing up to numbers 900,000 but crashes right after.
template<class writeIter>
void quicksort(writeIter begin, writeIter end)
{
if (begin!= end) {
int diff = end-begin;
if (diff > 2) {
writeIter pivot = ((end-begin) / 2) + begin;
writeIter itFirst = begin;
writeIter itSecnd = end-1;
auto pivotVal = *pivot;
swap(*pivot, *(end-1));
while (itFirst < itSecnd) {
if (*itFirst > pivotVal) {
while (*itSecnd > pivotVal && itSecnd > itFirst) --itSecnd;
if (itSecnd > itFirst)
swap(*itFirst, *itSecnd);
}
++itFirst;
}
swap(*itSecnd, *(end-1));
quicksort(begin, itSecnd);
quicksort(itSecnd, end);
}
else if (diff == 2)
if (*begin > *(begin+1))
swap(*begin, *(begin+1));
}
}
Yes, it's the naive quick sort. But you choose the middle element instead of the last element as your pivot.
To gain a better performance on almost all vectors, you can:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.