Back to: Python Data Structure and Algorithims
0
Implementing the Quicksort Function in Python
Now that we have our pivot function ready, it’s time to implement Quicksort.
Quicksort is a recursive sorting algorithm that repeatedly uses the pivot to partition the list into smaller parts and then sorts each part.
Step 1: Understand How Quicksort Uses Pivot
-
The pivot function takes a list (or sublist) and:
-
Rearranges elements so that all smaller elements are to the left.
-
All larger elements are to the right.
-
Returns the pivot index in its correct sorted position.
-
-
Quicksort then:
-
Recursively calls itself on the left side of the pivot.
-
Recursively calls itself on the right side of the pivot.
-
Step 2: Writing the Recursive Quicksort Helper
We first create a helper function to handle recursion with indices:
def quicksort_helper(lst, left, right):
if left < right: # Base case: stop when left >= right
pivot_index = pivot(lst, left, right) # Partition list and get pivot index
# Recursively sort left side
quicksort_helper(lst, left, pivot_index – 1)
# Recursively sort right side
quicksort_helper(lst, pivot_index + 1, right)
return lst
Step 3: Simplify the User Interface
We can now wrap the helper function so users don’t need to pass indices: