简体   繁体   中英

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) . (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.

  1. When you fill a vector [max-num, 0], it's actually not the worst-case scenario at all. Because each time you choose the middle element as the pivot, you divide the vector into two parts with almost the same size, so the time complexity is O(nlogn).
  2. However, when you fill the unsorted vector [0, max-num/2] then [max-num/2, 0], it's the worst-case for you algorithm as you divide the vector into two parts with one extremely long and one extremely short. So the time complexity is O(n^2).

To gain a better performance on almost all vectors, you can:

  • pick a random element as your pivot
  • pick three random elements and choose the second largest one
  • when the size of vector is small enough, eg, smaller than 10, apply insert sort on it
  • to deal with the situation that all elements are close to each other, you can do some extra work before recursively sorting subvectors to skip the elements equal to the pivot

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM