0

This is a standard recursive quickSort implementation, and it succeeds at sorting larger lists for unsorted items but not for "pre-sorted" items. I knew it would take longer, but not fail altogether. Any possible improvements?

void quickSort(int *array, size_t count) {
    int pivot = array[count - 1];
    int max_index = 0;
    for (size_t i = 0; i < count - 1; ++i) 
    {
        if (array[i] < pivot) {
            swap(array[i], array[max_index]);
            ++max_index;
        }
    }
    swap(array[max_index], array[count - 1]);

    if (max_index > 1)
        quickSort(array, max_index);
    if (count - max_index - 1 > 1)
        quickSort(array + max_index + 1, count - max_index - 1);
}
sabowsky
  • 1
  • 1
  • 1
    What does "fails" mean? – JohnFilleau May 15 '20 at 22:18
  • Can you show an example of input that fails, along with the output? – cigien May 15 '20 at 22:19
  • Now executing your Quick Sort of 9999 items. Your Quick Sort took 0.005833 Seconds. Now Executing your Quick Sort of 9999 pre-sorted items. (process 16128) exited with code -1073741571. ^^^^That's the output I receive, and it's a tester program for when I put in 9,999 items to sort. It doesn't output the time indicating something went wrong altogether, maybe stack overflow. – sabowsky May 15 '20 at 22:24
  • Which `swap` function are you using? – JaMiT May 15 '20 at 22:25
  • 1
    Using the library std::swap – sabowsky May 15 '20 at 22:26
  • @sabowsky try using `int count` instead of `size_t count` – Vladimir Nikitin May 15 '20 at 22:27
  • @sabowsky Tester programs can be useful for finding errors, but they might not be the best tool for debugging. A good next step for you would be to create your own test program where you give your function a pre-sorted array of, let's say, three elements and you step through your code with a debugger. – JaMiT May 15 '20 at 22:27
  • @JaMiT The issue is that it works fine on 100 items, so I'm thinking it might have to do with the style of recursion and stack overflow – sabowsky May 15 '20 at 22:30
  • @VladimirNikitin not an option, but thank you haha. – sabowsky May 15 '20 at 22:30

1 Answers1

0

I think your problem is the choice of a pivot value. You're using the rightmost value (array[count-1]) which can lead to worst-case behavior for an already sorted sequence. You create a partition with size 1 and another partition with size n-1. This causes a chain of n-1 recursive calls, leading to poor performance O(N2) or a stack overflow.

You should consider alternatives like:

  • A random index
  • The middle index
  • The median of three indexes (first, middle, last)
  • Something more complicated like a median of medians (ninther)
Blastfurnace
  • 18,411
  • 56
  • 55
  • 70