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
- Choose a Pivot Point
- Example: Last item in the sequence
- Pivot: Number to base comparisons of other numbers
- Partitioning the Sequence
- Iterate through the sequence
- Numbers < Pivot: One list
- Numbers > Pivot: Another list
- 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
- Define Function: Name it
quicksort, takes an unsorted sequence.
- Base Case: If the sequence length ≤ 1, return the sequence.
- Pivot Using
pop Method
- Remove and return the last element as pivot.
- Partition Lists: Two lists (
items_greater and items_lower).
- Comparison and Distribution
- Iterate through sequence, append items to respective lists based on comparison with pivot.
- Recursive Call: Return sorted result by combining the results of recursive
quicksort calls on the sublists.
- 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!