Quicksort partitions the input around a pivot and recursively sorts the two sides. This implementation uses the first value as its pivot. Balanced partitions give Θ(n log n) time. Repeatedly choosing an extreme value gives Θ(n²) time, including on already sorted input with this pivot rule.
Simple example
Choose 2 as the pivot. Move 1 to its left and 3 to its right. Each side now has one item.
Start3 1 2
Result1 2 3
lesson.py
values = [3, 1, 2]
pivot = values[2]
boundary = 0
i = 0
while i < 2:
if values[i] < pivot:
saved = values[i]
values[i] = values[boundary]
values[boundary] = saved
boundary += 1
i += 1
values[2] = values[boundary]
values[boundary] = pivot
i = 0
while i < 3:
print(values[i])
i += 1
Output
1
2
3
Everyday examples
Divide parcels by a sample weight
Weights are 8, 2 and 5 kilograms. Use 5 as the pivot. What goes on each side?
Start8 2 5
Result2 • 5 • 8
Two is lighter and eight is heavier. The pivot now separates the two groups.
Handle equal book prices
Every book costs 4. What would a three-way partition produce?
Start4 4 4
Result∅ • 4 4 4 • ∅
The equal group contains every book. Neither outer group needs more work.
Notice a poor pivot
Dates 1, 2, 3 and 4 are in order. Always choose the last date. What happens on the first split?
Start1 2 3 4
Result1 2 3 • 4 • ∅
One group still holds three items. Repeating this pattern wastes comparisons.
Cost and limits
Balanced partitions usually lead to O(n log n) work. Repeatedly choosing an extreme pivot can take O(n²).
Before Sorting:
15 3 12 6 -9 9 0
After Sorting:
-9 0 3 6 9 12 15
Advertisements
Walk through the example
Start with [15, 3, 12, 6, -9, 9, 0].
Use the first value, 15, as the pivot. Scan inward from both ends.
Advance the left index while its value is at most the pivot and the index is below the upper bound. Move the right index left while its value exceeds the pivot.
If the indices have not met, exchange the two misplaced values and continue scanning.
When the indices meet or cross, exchange the first value with the value at the right index. The pivot is now in its final position.
Recursively sort the ranges before and after that position. A range with fewer than two elements is already sorted.
Quick Sort Implementation in Python with explanation
Python source code
class QuickSortExample:
def __init__(self):
pass
def quickSort(self, arr, low, high):
if(low < high):
# Find the pivot index of the lower bound of an array
pivot = self.partition(arr, low, high)
# Apply Divide and conquer strategy
# to sort the left side and right side of an array
# respective to the pivot position
# Left hand side array
self.quickSort(arr, low, pivot - 1)
#Right hand side array
self.quickSort(arr, pivot + 1, high)
return arr
def partition(self, arr, low, high):
# Pick a lowest bound element as an pivot value
pivot = arr[low]
i = low
j = high
while(i < j):
# Increment the index value (i.e. i )
# till the piovt value is greater than or equal the left most values
while(arr[i] <= pivot and i < high):
i += 1
# Increment the index value (i.e. j )
# till the piovt value is less than the right most values
while(arr[j] > pivot and j > low):
j -= 1
# Interchange the values of present
# in the index i and j of an array only if i is less than j
if(i < j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
# Interchange the element in j's poisition to the lower bound of an array
# and place the Pivot element to the j's position
arr[low] = arr[j]
arr[j] = pivot
return j
def printArray(self, arr):
# Loop the item and print each item in the console with white space seperated
string = " ".join([str(item) for item in arr])
print(string)
obj = QuickSortExample()
arr = [15, 3, 12, 6, -9, 9, 0]
print("Before Sorting: ")
obj.printArray(arr)
result = obj.quickSort(arr, 0, len(arr) - 1)
print("After Sorting: ")
obj.printArray(result)
Output
Before Sorting:
15 3 12 6 -9 9 0
After Sorting:
-9 0 3 6 9 12 15