[英]Naming the sorting algorithm. Is it QuickSort?
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)
. 1.当我对向量
[max-num, 0]
填充时(最坏的情况),我得到的结果要好于O(n^2)
。 (I'm not even sure if I even wrote a quicksort anymore). (我什至不能确定我是否再写过Quicksort)。
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. 2.当我混合范围时,例如:我先填充未排序的向量
[0, max-num/2]
然后再填充[max-num/2, 0]
,这很奇怪,它崩溃到数字900,000,但随后崩溃。
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: 要在几乎所有矢量上获得更好的性能,您可以:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.