Skip to content
Advertisement

(python) quicksort working for ordered data, but not for unordered data

I am working on an implementation of recursive quicksort in python. I am working with very large data sets (10,000 – 1,000,000 elements). When feeding it ordered data (i.e. changing an array sorted from largest -> smallest to smallest -> largest) it works fine. But when giving it unordered data, it doesn’t seem to work at all.

I’m using a 3-way pivot that counts elements that are equal to the pivot (dutch national flag problem) and, if the data is larger than 101 (remember it’s recursive), it uses a median of first, middle, and last elements in the array partition when selecting the pivot.

Slice of output from a random set of 10,000 elements:

JavaScript

As you can see, it seems to have a certain pattern to it. I’ve increased the recursion limit so I know that’s not the problem, but it almost seems like it’s only partially sorting the input. Like I mentioned, it works fine for an array that’s already sorted in reverse order, which is what mystifies me.

My code:

JavaScript

Advertisement

Answer

I figured it out. It was just a small typo in qs_part(). while mid <= lo should have been while mid <= hi

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement