Merge Sort
Learn how the Merge Sort algorithm organizes data using a divide and conquer strategy.
Warm Up: Divide and Conquer
Status: SPLITTING
The list must be divided. Click any sublist with multiple cards to split it in half.
What is Merge Sort?
The merge sort algorithm has two parts: splitting items and merging items. It starts by splitting a list into halves called sublists, repeating until each sublist contains only single items.
The merge sort algorithm is an example of a divide and conquer approach. It breaks down a problem into smaller parts until they are simple enough to solve directly.
- Splitting: Repeatedly dividing the group into half until you have separate groups with a single item.
- Merging: Reassembling groups by comparing the first items of two sublists and placing the lowest value into a new ordered list.
Numerical Example: Olympic Medals
Sorting medal counts: [15, 25, 13, 29, 18].
1. Visualising the Split & Merge
MERGE SORT
Click start to begin the visualization
Try it yourself!
The list [10, 12, 6, 9, 5, 6, 5] has been split once. How will the sublists look after the second split?
Sorting Words: Computer Scientists
Sorting famous pioneers alphabetically: ["Ada Lovelace", "Grace Hopper", "Anita Borg", "Margaret Hamilton", "Annie Easley", "Joan Clarke", "Mary Wilkes", "Karen Spärck Jones"].
2. Alphabetical Merge Sort
MERGE SORT
Click start to begin the visualization
Algorithm Implementation
The instructions for merge sort involve a recursive logic of splitting and merging.
Merge Sort Pseudocode
Sublists State
Status
Idle
Ready to trace...
def merge_sort(items):
if len(items) <= 1:
return items
mid = len(items) // 2
left = merge_sort(items[:mid])
right = merge_sort(items[mid:])
return merge(left, right)
def merge(left, right):
result = []
while left and right:
if left[0] <= right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
result.extend(left if left else right)
return result# Merge sort is highly efficient for large datasets because it uses a divide and conquer strategy, reducing the total number of comparisons.
Efficiency Scenarios
Unlike Bubble Sort, Merge Sort always splits the list regardless of its initial order.
Best Case
Smallest number of comparisons during merging.
MERGE SORT
Click start to begin the visualization
Worst Case
Every item must be compared at each stage.
MERGE SORT
Click start to begin the visualization
Fill the Gaps
Order the Steps
Arrange the steps of the Merge Sort algorithm.
Available Steps:
Your sequence:
Click items above to build your sequence
Keywords Memory Game
A-Level Only: Efficiency of Merge Sort
Let's analyse the Time and Space complexity of Merge Sort using Big O notation. The graph below highlights why Merge Sort is so powerful: its Best, Average, and Worst Case Time Complexity are all Linearithmic O(n log n). However, this speed comes at the cost of requiring more memory, leading to a Linear Space Complexity of O(n).