Sorting: Bubble, Merge & Quick
Data Structures & Algorithms · Searching & Sorting · Intermediate · 18 min
Put things in order, and learn divide & conquer on the way.
Two sorted piles of cards face up. You keep taking the smaller of the two top cards and laying it on a new pile, until one pile runs out and you drop the rest on top.
The idea in everyday words
Sorting a hand of cards. Bubble sort = keep swapping neighbours until nothing moves (slow). Merge sort = split the deck between friends, each sorts a small pile, then you merge the sorted piles by always taking the smaller top card (fast).
Bubble sort: easy but slow O(n²)
Compare neighbours, swap if out of order. After each pass the biggest item 'bubbles' to the end. Run it and watch each pass:
nums = [5, 1, 4, 2, 8]
for end in range(len(nums) - 1, 0, -1):
swapped = False
for i in range(end):
if nums[i] > nums[i + 1]:
nums[i], nums[i + 1] = nums[i + 1], nums[i]
swapped = True
print("after pass:", nums)
if not swapped:
break # nothing moved, so the list is already sorted
The swapped flag is what "until nothing moves" means in code: if a whole pass makes no swap, the list is sorted and we stop early. On an already sorted list that is one pass, O(n). Without the flag, bubble sort always does every pass, so even sorted input costs O(n²). The worst case (reversed input) is O(n²) either way.
Merge sort: divide & conquer O(n log n)
- Split the list in half until pieces have 1 item (already sorted!).
- Merge two sorted halves by repeatedly taking the smaller front item.
def merge(a, b):
out, i, j = [], 0, 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
return out + a[i:] + b[j:]
def merge_sort(nums):
if len(nums) <= 1:
return nums
mid = len(nums) // 2
return merge(merge_sort(nums[:mid]), merge_sort(nums[mid:]))
print(merge_sort([38, 27, 43, 3, 9, 82, 10]))
Quick sort & built-ins
Quick sort: pick a pivot, put smaller items left and bigger right, recurse. Average O(n log n), worst O(n²).
In interviews you usually just call the built-in sort (Python's Timsort, O(n log n)), but know why it's O(n log n) and how to sort by a key:
people = [("ana", 31), ("bo", 25), ("cy", 40)]
print(sorted(people, key=lambda p: p[1])) # by age
print(sorted(people, key=lambda p: -p[1])) # oldest first
Step by step
- Split:
[38,27,43,3] → [38,27] and [43,3]
- Split again:
[38] [27] [43] [3]: single items are sorted
- Merge pairs:
[27,38] and [3,43]
- Merge halves:
take 3, 27, 38, 43 → [3,27,38,43]
Code example
def quick_sort(nums):
if len(nums) <= 1:
return nums
pivot = nums[len(nums) // 2]
left = [x for x in nums if x < pivot]
mid = [x for x in nums if x == pivot]
right = [x for x in nums if x > pivot]
return quick_sort(left) + mid + quick_sort(right)
print(quick_sort([9, 3, 7, 1, 8, 2]))Complexity
- Time: Bubble O(n²) · Merge O(n log n) · Quick O(n log n) on average, O(n²) in the worst case
- Space: Bubble O(1) · Merge O(n) · Quick: O(log n) stack on average when it partitions in place (O(n) with bad pivots); the list-building quick_sort shown here makes new lists: about O(n) extra on average, up to O(n²) in the worst case, because with bad pivots every level of the recursion keeps its own smaller list alive (n - 1, then n - 2, ...)
Interview tips
'Merge two sorted lists/arrays' is extremely common.
JS gotcha: [10, 9, 1].sort() sorts as strings! Use .sort((a, b) => a - b).
Kth largest → quickselect or a heap.
Challenge: Merge Two Sorted Lists
Given two sorted lists, return one sorted list containing all items. Don't call a sort: walk both lists with two pointers!
Example: merge_sorted([1, 4, 7], [2, 3, 9]) → [1, 2, 3, 4, 7, 9]
Solve it in the browser with tests, hints and an AI coach.
Practice problems
- Merge Sorted Array (Easy)
- Merge Two Sorted Lists (Easy)
- Sort Colors (Medium)
- Sort an Array (Medium)
More in Searching & Sorting
Previous: Binary Search · Next: Beyond Comparison Sorts