Pick a pivot, split the rest into smaller and larger, and sort each side the same way.
Python · intermediate · 8 min · 32 steps · free
def quick_sort(items):
if len(items) <= 1:
return items
pivot = items[0]
smaller = [x for x in items[1:] if x < pivot]
larger = [x for x in items[1:] if x >= pivot]
return quick_sort(smaller) + [pivot] + quick_sort(larger)
print(quick_sort([4, 7, 2, 9, 1]))quick_sort(). Its body does not run yet: it runs each time the function is called.quick_sort(), with items = [4, 7, 2, 9, 1]. It gets its own names.len(items) <= 1 is false, so the block under it is skipped.smaller: [2, 1].larger: [7, 9].smaller the same way.len(items) <= 1 is false, so the block under it is skipped.pivot is created with the value 2.smaller is created and points to a new list: [1].larger is created and points to a new list: [].quick_sort() #3, with items = [1]. It gets its own names.len(items) <= 1 is true, so the block under it runs.items.quick_sort() #3 has finished. Python calls quick_sort() #3, with items = []. It gets its own names.len(items) <= 1 is true, so the block under it runs.items.quick_sort() #3 has finished, so its names are gone.quick_sort() #2 has finished. Python calls quick_sort() #2, with items = [7, 9]. It gets its own names.len(items) <= 1 is false, so the block under it is skipped.pivot is created with the value 7.smaller is created and points to a new list: [].larger is created and points to a new list: [9].quick_sort() #3, with items = []. It gets its own names.len(items) <= 1 is true, so the block under it runs.items.quick_sort() #3 has finished. Python calls quick_sort() #3, with items = [9]. It gets its own names.len(items) <= 1 is true, so the block under it runs.items.quick_sort() #3 has finished, so its names are gone.quick_sort() #2 has finished, so its names are gone.Answer: O(n²). Every split is lopsided.
Answer: In its final place