Standard algorithms (bubble sort, insertion sort, merge sort, quick sort, Dijkstra’s shortest path algorithm, A* algorithm, binary search and linear search).
2.3.1 Algorithms
Algorithms — Note 6 of 6
Candidates need to understand the need for searching and sorting algorithms and the pre-conditions required for each. Candidates need to be able to perform, and read, trace and write code for, bubble sort, insertion sort, merge sort, quick sort, binary search and linear search. Candidates need to be able to calculate the shortest path using Dijkstra’s shortest path algorithm and the A* algorithm, and read and trace code that performs them.
You need to understand how each standard algorithm works, be able to carry it out by hand on a set of data, and be able to read, trace and write code for the searching and sorting algorithms. For Dijkstra's and A*, you need to read and trace code rather than write it.
function binarySearch(list, target)
low = 0
high = list.length - 1
while low <= high
mid = (low + high) DIV 2
if list[mid] == target then
return mid
elseif list[mid] < target then
low = mid + 1
else
high = mid - 1
endif
endwhile
return -1
endfunctiondef bubble_sort(data):
swapped = True
passes = 0
while swapped:
swapped = False
for i in range(len(data) - 1 - passes):
if data[i] > data[i + 1]:
data[i], data[i + 1] = data[i + 1], data[i]
swapped = True
passes += 1
return datadef insertion_sort(data):
for i in range(1, len(data)):
current = data[i]
pos = i
while pos > 0 and data[pos - 1] > current:
data[pos] = data[pos - 1] # shift larger items right
pos -= 1
data[pos] = current
return datadef merge_sort(data):
if len(data) <= 1:
return data
mid = len(data) // 2
left = merge_sort(data[:mid])
right = merge_sort(data[mid:])
result = []
i = j = 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
return result + left[i:] + right[j:]def quick_sort(data):
if len(data) <= 1:
return data
pivot = data[0]
smaller = [x for x in data[1:] if x < pivot]
larger = [x for x in data[1:] if x >= pivot]
return quick_sort(smaller) + [pivot] + quick_sort(larger)def dijkstra(graph, start):
# graph: {node: {neighbour: weight}}
distances = {node: float("inf") for node in graph}
distances[start] = 0
unvisited = list(graph)
while unvisited:
current = min(unvisited, key=lambda n: distances[n])
unvisited.remove(current)
for neighbour, weight in graph[current].items():
new_distance = distances[current] + weight
if new_distance < distances[neighbour]:
distances[neighbour] = new_distance
return distances
graph = {"A": {"B": 4, "C": 1}, "B": {"D": 1},
"C": {"B": 2, "D": 5}, "D": {}}
print(dijkstra(graph, "A")) # {'A': 0, 'B': 3, 'C': 1, 'D': 4}