Quicksort Algorithm Tutorial

Jul 1, 2024

Quicksort Algorithm Tutorial by Derek

Overview

  • Presenter: Derek
  • Topic: Algorithm tutorial series focusing on Quicksort Algorithm

Introduction

  • Quicksort Algorithm: Sorts an unsorted sequence into ascending (or descending) order.
  • Example used: Ascending order.

Steps of Quicksort Algorithm

  1. Choose a Pivot Point
    • Example: Last item in the sequence
    • Pivot: Number to base comparisons of other numbers
  2. Partitioning the Sequence
    • Iterate through the sequence
    • Numbers < Pivot: One list
    • Numbers > Pivot: Another list
  3. Recursion
    • Apply the same method to new lists created

Important Concepts

  • Pivot Selection
    • Can be the first, last, middle, or median of three numbers.
  • Completing a Pass
    • After one pass, the pivot is positioned correctly in the sorted list.
  • Recursive Sorting
    • Apply Quicksort to sublists formed by partitioning until sublists are sorted.

Efficiency

  • Worst-case Complexity: O(n^2)
  • Average-case Complexity: O(n log n)

Python Implementation

  1. Define Function: Name it quicksort, takes an unsorted sequence.
  2. Base Case: If the sequence length ≤ 1, return the sequence.
  3. Pivot Using pop Method
    • Remove and return the last element as pivot.
  4. Partition Lists: Two lists (items_greater and items_lower).
  5. Comparison and Distribution
    • Iterate through sequence, append items to respective lists based on comparison with pivot.
  6. Recursive Call: Return sorted result by combining the results of recursive quicksort calls on the sublists.
  7. Testing: Print the result and verify the sorting.

Example Code

# Define the quicksort function def quicksort(sequence): length = len(sequence) if length <= 1: return sequence else: pivot = sequence.pop() items_greater = [] items_lower = [] for item in sequence: if item > pivot: items_greater.append(item) else: items_lower.append(item) return quicksort(items_lower) + [pivot] + quicksort(items_greater) # Testing the quicksort function print(quicksort([33, 10, 55, 71, 29, 5, 70]))

Performance

  • Advantages: O(n log n) complexity makes it preferred for large datasets.

Conclusion

  • Quicksort is a powerful and efficient sorting algorithm frequently used due to its efficiency and simplicity.

Note: If any questions or comments, reach out!