OCR H446, section 2.3.1 (f)
These are the standard algorithms you need to know: how they work, how to trace them, and their complexity (2.3.1 (d)).
Searching
Linear search
Check each item in turn, from the start, until the target is found or the list ends.
def linear_search(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1
- Works on unsorted data, and on linked lists.
- Worst case : the item is last or missing.
Binary search
Needs a sorted list. Compare the target with the middle item, and discard the half that can't contain it. Repeat.
def binary_search(items, target):
low = 0
high = len(items) - 1
while low <= high:
mid = (low + high) // 2
if items[mid] == target:
return mid
elif items[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
Trace: find 23 in [4, 8, 15, 23, 42, 57, 61].
low |
high |
mid |
items[mid] |
Action |
|---|---|---|---|---|
| 0 | 6 | 3 | 23 | Found at index 3 |
Find 57 instead:
low |
high |
mid |
items[mid] |
Action |
|---|---|---|---|---|
| 0 | 6 | 3 | 23 | 57 is larger: low = 4 |
| 4 | 6 | 5 | 57 | Found at index 5 |
- Worst case .
Sorting
Sorting the list [5, 2, 9, 1] into ascending order.
Bubble sort
Compare neighbours and swap if they're in the wrong order. Repeat passes until a pass makes no swaps. The largest values "bubble up" to the end.
def bubble_sort(items):
n = len(items)
swapped = True
while swapped:
swapped = False
for i in range(n - 1):
if items[i] > items[i + 1]:
items[i], items[i + 1] = items[i + 1], items[i]
swapped = True
n = n - 1
return items
Trace of [5, 2, 9, 1]:
| Pass | Comparisons and swaps | List after the pass |
|---|---|---|
| 1 | 5>2 swap; 5<9; 9>1 swap | [2, 5, 1, 9] |
| 2 | 2<5; 5>1 swap | [2, 1, 5, 9] |
| 3 | 2>1 swap | [1, 2, 5, 9] |
| 4 | no swaps | [1, 2, 5, 9] (stop) |
- time, space. With the swapped flag, it's for a sorted list.
Insertion sort
Treat the left part as sorted. Take the next item and insert it into its correct place in the sorted part, by shifting larger items right.
def insertion_sort(items):
for i in range(1, len(items)):
value = items[i]
j = i - 1
while j >= 0 and items[j] > value:
items[j + 1] = items[j]
j = j - 1
items[j + 1] = value
return items
Trace of [5, 2, 9, 1]:
| Step | Item inserted | List after |
|---|---|---|
| Start | sorted [5], still to do [2, 9, 1] |
|
| 1 | 2 | sorted [2, 5], still to do [9, 1] |
| 2 | 9 | sorted [2, 5, 9], still to do [1] |
| 3 | 1 | sorted [1, 2, 5, 9] |
- worst case, for nearly sorted data, space.
Merge sort
Divide and conquer (2.2.2 (d)): split the list in half repeatedly, until each part has one item, then merge pairs of sorted parts back together.
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(a, b):
result = []
i = j = 0
while i < len(a) and j < len(b):
if a[i] <= b[j]:
result.append(a[i])
i += 1
else:
result.append(b[j])
j += 1
return result + a[i:] + b[j:]
- always, extra space. Stable.
Quick sort
Divide and conquer with a pivot: choose a pivot, partition the others into those smaller and larger, then sort each part recursively.
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)
Trace of [5, 2, 9, 1]: pivot 5. Smaller [2, 1], larger [9]. Sort [2, 1]: pivot 2, smaller [1], larger [] giving [1, 2]. Result [1, 2] + [5] + [9] = [1, 2, 5, 9].
- average. Worst case when the pivot is always the smallest or largest (for example the first item of an already sorted list). Choosing the middle or a random pivot avoids this. The in-place version needs very little extra space.
Shortest paths
Both work on a weighted graph, stored here as a dictionary:
graph = {
"A": {"B": 4, "C": 2},
"B": {"A": 4, "D": 5},
"C": {"A": 2, "D": 8, "E": 10},
"D": {"B": 5, "C": 8, "E": 2, "F": 6},
"E": {"C": 10, "D": 2, "F": 3},
"F": {"D": 6, "E": 3},
}
Dijkstra's shortest path algorithm
Finds the shortest path from a start node to every other node (weights must be non-negative).
Method:
- Give the start distance 0, and every other node distance infinity.
- Mark all nodes unvisited.
- Pick the unvisited node with the smallest distance. Mark it visited.
- For each neighbour, work out distance to current + edge weight. If it's less than the neighbour's recorded distance, update it and record the current node as its previous node.
- Repeat from step 3 until all nodes are visited (or the target is).
- Follow the previous nodes back from the target to get the path.
def dijkstra(graph, start):
dist = {node: float("inf") for node in graph}
prev = {node: None for node in graph}
dist[start] = 0
unvisited = set(graph)
while unvisited:
current = min(unvisited, key=lambda n: dist[n])
unvisited.remove(current)
for nb, w in graph[current].items():
new = dist[current] + w
if new < dist[nb]:
dist[nb] = new
prev[nb] = current
return dist, prev
Trace from A:
| Step | Visit | A | B | C | D | E | F |
|---|---|---|---|---|---|---|---|
| Start | 0 | ∞ | ∞ | ∞ | ∞ | ∞ | |
| 1 | A | 0 | 4 | 2 | ∞ | ∞ | ∞ |
| 2 | C (2) | 0 | 4 | 2 | 10 | 12 | ∞ |
| 3 | B (4) | 0 | 4 | 2 | 9 | 12 | ∞ |
| 4 | D (9) | 0 | 4 | 2 | 9 | 11 | 15 |
| 5 | E (11) | 0 | 4 | 2 | 9 | 11 | 14 |
| 6 | F (14) | 0 | 4 | 2 | 9 | 11 | 14 |
The shortest distance from A to F is 14. Following the previous nodes back from F: F ← E ← D ← B ← A, so the path is A, B, D, E, F.
- Simple version (V is the number of nodes). Faster with a priority queue.
A* algorithm
An improved Dijkstra's for finding a path to one goal. It chooses the next node using
- : the actual cost so far from the start to .
- : a heuristic estimate of the cost from to the goal (for example straight-line distance).
- It always expands the node with the lowest .
The heuristic steers the search towards the goal, so fewer nodes are explored than with Dijkstra's. For the shortest path to be guaranteed, must never overestimate the true cost (it must be admissible).
Method:
- Put the start in an open list, with .
- Take the node with the lowest from the open list.
- If it's the goal, stop and trace back the path.
- Otherwise, for each neighbour, calculate (cost to reach it through the current node), and . Add or update it in the open list if this is a better route.
- Move the current node to the closed list (done). Repeat from step 2.
With the graph above, going from A to F and heuristic estimates : A 10, B 9, C 9, D 5, E 3, F 0:
| Step | Expand | Neighbours: , |
|---|---|---|
| 1 | A ( = 10) | B: 4, 13. C: 2, 11 |
| 2 | C (11) | D: 10, 15. E: 12, 15 |
| 3 | B (13) | D: 9, 14 (better, replaces 15) |
| 4 | D (14) | E: 11, 14 (better). F: 15, 15 |
| 5 | E (14) | F: 14, 14 (better) |
| 6 | F (14) | Goal: stop |
Path: A, B, D, E, F with cost 14, the same as Dijkstra's, but it didn't need to visit every node first, and with a larger graph the saving is much greater.
| Dijkstra's | A* | |
|---|---|---|
| Finds | Shortest path to all nodes | Shortest path to one goal |
| Chooses next node by | Lowest (cost so far) | Lowest |
| Needs a heuristic? | No | Yes |
| Speed | Explores in all directions | Usually faster, heads for the goal |
| If | Becomes Dijkstra's |
Summary
| Algorithm | Time (worst) | Space | Key point |
|---|---|---|---|
| Linear search | Any data | ||
| Binary search | Sorted data | ||
| Bubble sort | Simple, swaps neighbours | ||
| Insertion sort | Good for nearly sorted | ||
| Merge sort | Divide and conquer, stable | ||
| Quick sort | , average | Pivot, usually fastest | |
| Dijkstra's | simple | Shortest path to all nodes | |
| A* | Depends on | Shortest path to one goal, uses a heuristic |
Worked example
Task: show the stages of an insertion sort and a merge sort on [7, 3, 5, 1], and state which is better for 1 million items.
Insertion sort: start with [7] sorted. Insert 3: [3, 7]. Insert 5: [3, 5, 7]. Insert 1: [1, 3, 5, 7].
Merge sort: split into [7, 3] and [5, 1], then into [7], [3], [5], [1]. Merge to [3, 7] and [1, 5]. Merge to [1, 3, 5, 7].
For 1 million items: insertion sort takes about steps, and merge sort about . Merge sort is better, although it needs extra memory.
Exam tip: you may be asked to trace an algorithm on given data: show each pass or step in a table. For Dijkstra's, keep the table of distances up to date and say which node you're visiting. For A*, remember . Know when each searching and sorting algorithm is suitable (2.3.1 (b)).
Check yourself
What must be true of a list before a binary search can be used?
It must be sorted.
How does a bubble sort know when to stop?
When a complete pass is made with no swaps, the list is sorted.
What is the worst case for quick sort, and what causes it?
O(n²), caused by the pivot always being the smallest or largest item, such as choosing the first item of an already sorted list.
What does merge sort do in its "combine" step?
It merges two sorted lists into one sorted list, by repeatedly taking the smaller of the front items.
How does A* differ from Dijkstra's algorithm?
A* adds a heuristic estimate of the remaining distance to the goal, so it chooses nodes by g + h and explores fewer nodes when looking for a path to one goal.
What does the heuristic in A* need to be, to guarantee the shortest path?
Admissible: it must never overestimate the true cost to the goal.