Of course. Here are several efficient Python implementations of Quick Sort, ranging from the classic educational version to a more robust and practical one.
I'll provide three main versions:
- The Classic In-Place Implementation (Lomuto Partition Scheme): The version you'll see in most textbooks. It's memory-efficient.
- A "Pythonic" Recursive Implementation: Very concise and easy to read, but uses more memory. Great for understanding the concept.
- The Recommended Robust Implementation: An iterative version with a better pivot strategy to avoid worst-case scenarios and recursion depth errors. This is the most "efficient" for real-world use if you must implement Quick Sort from scratch.
1. The Classic In-Place Implementation (Lomuto Partition)
This is the standard, memory-efficient implementation. It sorts the list "in-place," meaning it doesn't create new lists, thus using O(log n) space for the recursion stack.
Key Idea:
- A
partition function selects a pivot element (here, the last one) and rearranges the array so that all elements smaller than the pivot are on its left, and all elements greater are on its right.
- The
quick_sort function then recursively calls itself on the two sub-arrays.
def quick_sort_lomuto(arr, low, high):
"""
Standard quick sort implementation using the Lomuto partition scheme.
Sorts the list in-place.
:param arr: The list to be sorted.
:param low: The starting index of the sub-array.
:param high: The ending index of the sub-array.
"""
if low < high:
# pi is the partitioning index, arr[pi] is now at the right place
pi = partition(arr, low, high)
# Recursively sort elements before partition and after partition
quick_sort_lomuto(arr, low, pi - 1)
quick_sort_lomuto(arr, pi + 1, high)
def partition(arr, low, high):
"""
This function takes the last element as pivot, places the pivot element at its
correct position in the sorted array, and places all smaller elements
to the left of the pivot and all greater elements to the right.
"""
# Choose the rightmost element as pivot
pivot = arr[high]
# i is the pointer for the greater element
i = low - 1
# Traverse through all elements and compare them with the pivot
for j in range(low, high):
if arr[j] <= pivot:
# If element smaller than pivot is found, swap it with the greater element pointed by i
i = i + 1
arr[i], arr[j] = arr[j], arr[i]
# Swap the pivot element with the greater element specified by i
arr[i + 1], arr[high] = arr[high], arr[i + 1]
# Return the position from where partition is done
return i + 1
# --- Example Usage ---
my_list = [8, 10, 1, 9, 3, 5, 4, 7, 2, 6]
print("Original list:", my_list)
# Call the quick sort function
quick_sort_lomuto(my_list, 0, len(my_list) - 1)
print("Sorted list: ", my_list)
Pros:
- Space Efficient: Sorts in-place, using O(log n) stack space on average.
Cons:
- Worst-Case: Can degrade to O(n²) time complexity if the pivot selection is poor (e.g., on an already sorted list).
- Can hit Python's recursion depth limit on very large lists.
2. A "Pythonic" Recursive Implementation
This version is elegant and easy to understand, leveraging list comprehensions. However, it's not in-place and uses significantly more memory, making it less efficient for large lists.
def quick_sort_pythonic(arr):
"""
A concise, recursive but not in-place version of quick sort.
Uses more memory due to the creation of new lists.
"""
if len(arr) <= 1:
return arr
else:
pivot = arr[len(arr) // 2] # Using middle element as pivot is a simple improvement
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick_sort_pythonic(left) + middle + quick_sort_pythonic(right)
# --- Example Usage ---
my_list = [8, 10, 1, 9, 3, 5, 4, 7, 2, 6]
print("Original list:", my_list)
sorted_list = quick_sort_pythonic(my_list)
print("Sorted list: ", sorted_list)
Pros:
- Readability: Extremely easy to read and understand the "divide and conquer" logic.
Cons:
- Memory Inefficient: Creates new sub-lists at each step, leading to O(n) space complexity in the worst case. Not suitable for large datasets.
3. Recommended: Robust Iterative Implementation
This is the most efficient and robust version. It avoids recursion, eliminating the risk of RecursionError on large lists, and uses a better pivot selection strategy ("median-of-three") to make the O(n²) worst-case scenario much less likely.
Key Improvements:
- Iterative: Uses an explicit stack (a list) instead of the function call stack.
- Median-of-Three Pivot: Chooses the pivot as the median of the first, middle, and last elements. This prevents worst-case performance on sorted or reverse-sorted data.
def quick_sort_iterative_robust(arr):
"""
A robust, iterative implementation of Quick Sort.
- Avoids recursion depth errors.
- Uses median-of-three pivot selection to avoid worst-case O(n^2).
- Sorts in-place.
"""
if len(arr) <= 1:
return
# The stack holds tuples of (low, high) for sub-arrays to be sorted
stack = [(0, len(arr) - 1)]
while stack:
low, high = stack.pop()
if low >= high:
continue
# --- Partitioning Logic with Median-of-Three Pivot ---
mid = low + (high - low) // 2
# Find the median of arr[low], arr[mid], arr[high]
if arr[low] > arr[mid]: arr[low], arr[mid] = arr[mid], arr[low]
if arr[low] > arr[high]: arr[low], arr[high] = arr[high], arr[low]
if arr[mid] > arr[high]: arr[mid], arr[high] = arr[high], arr[mid]
# Now arr[mid] is the median. Swap it to the end to use as pivot
# This simplifies the partition logic (Hoare partition is often used here,
# but we can adapt Lomuto). Let's stick with a Lomuto-style partition.
pivot = arr[mid]
arr[mid], arr[high] = arr[high], arr[mid] # Move pivot to the end
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
# Place pivot in its final position
arr[i + 1], arr[high] = arr[high], arr[i + 1]
pi = i + 1
# --- End Partition ---
# Push the smaller sub-array to the stack first
# This keeps the stack size minimal (log n)
if pi - 1 - low < high - (pi + 1):
stack.append((low, pi - 1))
stack.append((pi + 1, high))
else:
stack.append((pi + 1, high))
stack.append((low, pi - 1))
# --- Example Usage ---
my_list = [8, 10, 1, 9, 3, 5, 4, 7, 2, 6, 11, 0, -1]
print("Original list:", my_list)
quick_sort_iterative_robust(my_list)
print("Sorted list: ", my_list)
# Test on a large list that might cause recursion errors
import random
large_list = [random.randint(0, 10000) for _ in range(5000)]
quick_sort_iterative_robust(large_list) # This will succeed
# quick_sort_lomuto(large_list, 0, len(large_list) - 1) # This might fail
print("Successfully sorted a large list.")
Summary and Recommendation
| Feature | Classic In-Place | Pythonic | Robust Iterative (Recommended) |
|---|
| Performance | O(n log n) avg, O(n²) worst | O(n log n) avg, O(n²) worst | O(n log n) avg, O(n²) rare |
| Space Complexity | O(log n) | O(n) | O(log n) |
| In-Place? | Yes | No | Yes |
| Recursion Error? | Possible on large lists | Possible on large lists | No |
| Use Case | Learning, interviews | Quick prototyping, small lists | Most reliable for custom implementation |
For most real-world Python applications, the best and most efficient way to sort is to use the built-in methods, which are highly optimized:
# Sorts the list in-place
my_list.sort()
# Returns a new sorted list
new_sorted_list = sorted(my_list)
Python's sort() uses Timsort, an advanced hybrid algorithm that is faster and more stable than a pure Quick Sort for many real-world data patterns. However, if you are specifically asked to implement an "efficient Quick Sort," the robust iterative version (#3) is your best choice.