Implementing the Quicksort Function in Python

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

  1. 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.

  2. 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:

def quicksort(lst):
       return quicksort_helper(lst, 0, len(lst) - 1)

Step 4: Example Walkthrough

Let’s take an example list:

my_list = [4, 6, 1, 7, 3, 2, 5]
sorted_list = quicksort(my_list.copy())
print("Original List:", my_list)
print("Sorted List:", sorted_list)

Step-by-step execution:

  1. Initial call: quicksort_helper(my_list, 0, 6)

    • Pivot = 4 → rearranges list → [2, 1, 3, 4, 6, 7, 5]

    • Pivot index = 3

  2. Left recursion: quicksort_helper(my_list, 0, 2)

    • Pivot = 2 → [1, 2, 3]

    • Pivot index = 1

    • Left: [1] → already sorted

    • Right: [3] → already sorted

  3. Right recursion: quicksort_helper(my_list, 4, 6)

    • Pivot = 6 → [5, 6, 7]

    • Pivot index = 5

    • Left: [5] → already sorted

    • Right: [7] → already sorted

  4. Combine results: Entire list is now sorted:

[1, 2, 3, 4, 5, 6, 7]

Step 5: Key Points

  • Pivot function is a helper that organizes elements and returns an index.

  • Base case: When left >= right, recursion stops.

  • In-place sorting: Quicksort modifies the original list.

  • Wrapping with a simple quicksort(lst) function avoids manually passing indices.

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to Top