Written by PChan on 2017-04-14
Key Idea: Partitioning¶
- The element you would be comparing against while partitioning or sorting via quicksort. This can be any element from the list.
One of the key component to quicksort is the partitioning algorithm. The goal of the algorithm is to group all elements less than a chosen pivot to the left of the pivot and all the elements greater than the pivot to the right of the pivot.
Given the list:
A = [1, 6, 3, 7, 2, 4]
Here is how you would partition the list:
- Start with the last element as the pivot
- Declare two variables: left and right; they would store the index as you move from the left and the index as you move from the right respectively
- Set them to 0 and n - 2 (for the second to last element) respectively
- Increment the left variable for each element that is smaller than the pivot or until it crosses with the right variable
- Decrement the right variable for each element that is greater than the pivot or until it crosses with the left variable
- If the two variables do not cross, swap the values at those indices
- Repeat steps 4 through 6 until the variables do cross
- Swap the pivot with the value at the index in which the variables cross
The General Algorithm¶
Once you have mastered the partitioning algorithm, the rest of quicksort is very easy.
- If the size of the list is 1, return the list
- Otherwise, pick a pivot and partition the list around the pivot
- Repeat the above steps for the left sublist and the right sublist
Here are some questions to ponder over (in order of ascending difficulty):
- Is there a best case scenario? A worst case scenario?
- How many times do you need to partition the list before the list is sorted?
- Determine the runtime of this algorithm. What is the ratio of the time it takes to sort the list and the size of the list?
Optional) How can you improve the basic quicksort algorithm?
Trace the quicksort algorithm when the pivot is the smallest or biggest element. What about when the pivot is the median of the list? Reflect on how this affects the performance of quicksort.