Sorting
Quick Sort (Lomuto)
Choose the last item as a pivot, partition smaller values to its left, then recurse on the two sides.
Algorithm
Basic Implementation
basic.py
def partition(arr, low, high):
pivot = arr[high]
i = low - 1
for j in range(low, high):
if arr[j] <= pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i + 1], arr[high] = arr[high], arr[i + 1]
return i + 1
def quick_sort(arr, low, high):
if low < high:
pivot_index = partition(arr, low, high)
quick_sort(arr, low, pivot_index - 1)
quick_sort(arr, pivot_index + 1, high)
arr = [4, 1, 5, 2, 3]
quick_sort(arr, 0, len(arr) - 1)
print(arr)
Complexity
- Time: O(n^2) worst, O(n log n) average
- Space: O(log n) average call stack
- Stable: no
Implementation notes
- Python stores
arras one list object, and quicksort mutates that list's element slots in place.pivot = arr[high]binds the pivot integer locally; it does not remove the pivot from the list. - The swaps use tuple-assignment syntax,
arr[i], arr[j] = arr[j], arr[i]andarr[i + 1], arr[high] = arr[high], arr[i + 1], so the right-hand references are read before either slot is overwritten. No replacement list is allocated, and swap temporaries are not part of the replayed state. range(low, high)scans up to but not including the pivot slot, andlow < highis the recursion guard for call-stack frames. The trace exposes the first partition with pivot3, then summarizes the left and right recursive ranges after the pivot lands at index2.
pivot
The final element is moved to the boundary between smaller and larger values.
partition
One scan rearranges the current range before the recursive calls.