Revision Library

Advanced Algorithms: Searching, Sorting and Path-Finding - Worksheets, Questions and Revision

12 original exam-style questions - 12 pages of questions with a full mark scheme - free printable PDF.

Download PDFJump to mark scheme (page 13)Read the revision guide
« Previous: Data Structures and Their OperationsNext: Databases and SQL »
Revision Library
revisionlibrary.co.uk
A-Level · Component 02: Algorithms and Programming

A2.6 Advanced Algorithms: Searching, Sorting and Path-Finding

OCR H446 · Calculators not allowed · about 155 minutes
Total Marks
Name: _______________________________    Date: ____ / ____ / ______
Answer ALL questions. Show all your working.
1
A vintage record shop in Brighton stores its catalogue of vinyl records as an array of catalogue numbers, kept sorted in ascending order. All arrays in this paper are indexed from 0, so an array with n items has indices 0 to n - 1. Pseudocode follows OCR's Exam Reference Language conventions (assignment <-, iteration FOR ... NEXT / WHILE ... ENDWHILE, selection IF ... ENDIF).

catalogueNumbers = [102, 118, 125, 130, 144, 151, 168, 172, 190, 205, 211, 230] (indices 0 to 11)
FUNCTION BinarySearch(list, target) RETURNS INTEGER
  low <- 0
  high <- LEN(list) - 1
  WHILE low <= high
    mid <- (low + high) DIV 2
    IF list[mid] = target THEN
      RETURN mid
    ELSE IF list[mid] < target THEN
      low <- mid + 1
    ELSE
      high <- mid - 1
    ENDIF
  ENDWHILE
  RETURN -1
ENDFUNCTION
(a)State one precondition that must be true about an array before binary search can be used on it correctly.(1)
(b)Complete the trace table below for the call BinarySearch(catalogueNumbers, 172).
lowhighmidlist[mid]comparison result
(4)
(c)State the value returned by the function call, and the number of comparisons of list[mid] with the target that were made.(2)
(d)The shop's catalogue grows to 2000 records, kept sorted. Using the formula ceil(log2(n + 1)) for the maximum number of comparisons binary search needs on a sorted list of n items, calculate the maximum number of comparisons needed to search the 2000-record catalogue.(2)
(e)Calculate the maximum number of comparisons linear search would need on the same 2000-record catalogue if a scanned record is not present, and state, with a reason based on Big O notation, which search algorithm is more time-efficient for this catalogue.(3)
(Total for Question 1 is 12 marks)
2
Both bubble sort and insertion sort can be optimised to recognise when a list is fully sorted and stop early. The list [1, 2, 3, 8, 4, 5] is nearly sorted: only the value 8 is out of place.
PROCEDURE BubbleSort(list)
  n <- LEN(list)
  DO
    swapped <- FALSE
    FOR i <- 0 TO n - 2
      IF list[i] > list[i + 1] THEN
        temp <- list[i]
        list[i] <- list[i + 1]
        list[i + 1] <- temp
        swapped <- TRUE
      ENDIF
    NEXT i
    n <- n - 1
  UNTIL swapped = FALSE
ENDPROCEDURE

FUNCTION InsertionSort(list)
  FOR i <- 1 TO LEN(list) - 1
    current <- list[i]
    j <- i - 1
    WHILE j >= 0 AND list[j] > current
      list[j + 1] <- list[j]
      j <- j - 1
    ENDWHILE
    list[j + 1] <- current
  NEXT i
ENDFUNCTION
(a)Complete the trace table below for BubbleSort([1, 2, 3, 8, 4, 5]), showing the list contents, whether any swap occurred, at the end of each pass, and the total number of comparisons made in that pass.
passlist at end of passswappedcomparisons this pass
1
2
(4)
(b)Complete the trace table below for InsertionSort([1, 2, 3, 8, 4, 5]), showing the value of current and the number of comparisons made against list[j] for each value of i. (For i = 1, 2 and 3, current is already in the correct place and no shifts occur.)
icurrentcomparisons madelist at end of this iteration
121[1, 2, 3, 8, 4, 5]
231[1, 2, 3, 8, 4, 5]
381[1, 2, 3, 8, 4, 5]
4
5
(4)
(c)State the total number of comparisons made by each algorithm across the whole sort, and state which algorithm required fewer comparisons to sort this nearly-sorted list.(3)
(d)Explain, with reference to your answers to part (c), why insertion sort is often preferred over bubble sort when sorting data that is already nearly in order, even though both algorithms have the same O(n2) worst-case time complexity.(2)
(Total for Question 2 is 13 marks)
3
The table below covers the searching and sorting algorithms studied so far in this topic.
(a)Complete the table below, giving the worst-case time complexity and the best-case time complexity (assuming any early-exit optimisation is used) of each algorithm, using Big O notation.
AlgorithmWorst-caseBest-case
Linear search
Binary search
Bubble sort
Insertion sort
Merge sort
(5)
(b)State which of the five algorithms in the table are described as adaptive (perform noticeably better on data that is already sorted or nearly sorted than their worst case), and explain why merge sort does not have this property.(3)
(Total for Question 3 is 8 marks)
4
The maximum number of key comparisons needed by merge sort to fully sort a list of n elements (where n is a power of 2) satisfies the recurrence relation:

C(n) = 2 x C(n / 2) + (n - 1), with C(1) = 0

This reflects recursively sorting two half-lists, each needing C(n/2) comparisons, and then merging the two sorted halves together using at most (n - 1) comparisons.
(a)Use the recurrence relation to calculate C(2), C(4) and C(8), showing your working at each stage.(3)
(b)It can be shown that, for n a power of 2, C(n) = n x log2(n) - n + 1. Verify that this formula gives the same value for C(8) as your answer to part (a).(2)
(c)Use the closed-form formula from part (b) to calculate C(16) and C(64), without using the recurrence relation directly.(4)
(d)A list of 64 elements is sorted using merge sort, then a second list of 64 elements is sorted using an O(n2) algorithm such as bubble sort, which needs up to n(n - 1) / 2 comparisons in the worst case. Calculate this worst-case number of comparisons for n = 64, and comment on what the comparison with your answer for C(64) shows about the relative growth rates of O(n log n) and O(n2).(3)
(Total for Question 4 is 12 marks)
5
The list [8, 3, 10, 1, 6, 14, 4] is sorted using the version of quicksort below, which always chooses the first element of the current list as the pivot.
FUNCTION QuickSort(list) RETURNS ARRAY
  IF LEN(list) <= 1 THEN
    RETURN list
  ENDIF
  pivot <- list[0]
  less <- []
  greaterEq <- []
  FOR i <- 1 TO LEN(list) - 1
    IF list[i] < pivot THEN
      APPEND(less, list[i])
    ELSE
      APPEND(greaterEq, list[i])
    ENDIF
  NEXT i
  RETURN QuickSort(less) + [pivot] + QuickSort(greaterEq)
ENDFUNCTION
(a)State the pivot used, and the resulting less and greaterEq lists, for the first call QuickSort([8, 3, 10, 1, 6, 14, 4]).(3)
(b)The algorithm then recursively calls QuickSort(less) and QuickSort(greaterEq). Complete the table below giving the pivot and the resulting less and greaterEq lists produced at each further recursive call on a list of more than one element.
callinput listpivotlessgreaterEq
2[3, 1, 6, 4]
3[6, 4]
4[10, 14]
(4)
(c)State the final sorted list returned by QuickSort([8, 3, 10, 1, 6, 14, 4]), and calculate the total number of element-to-pivot comparisons made across the whole sort (i.e. summing the comparisons made in every recursive call).(3)
(d)State the average-case time complexity of quicksort, and explain briefly why this typically holds when, as in this example, the pivot splits the list into two roughly similar-sized parts at each level of recursion.(2)
(Total for Question 5 is 12 marks)
6
The same QuickSort algorithm from the previous question (pivot always chosen as list[0]) is now applied to a list that is already sorted in ascending order: [2, 5, 7, 9, 12, 15] (6 elements).
(a)State the pivot, and the resulting less and greaterEq lists, for the first call QuickSort([2, 5, 7, 9, 12, 15]).(2)
(b)Explain why, for this sorted input with this pivot-choice strategy, every recursive call will produce an empty less list and a greaterEq list containing all of the remaining elements.(2)
(c)Complete the table below showing the number of element-to-pivot comparisons made at each level of recursion, continuing until the list is fully sorted, and state the total number of comparisons made overall.
levellist size at this levelcomparisons made
165
25
34
43
52
61
(3)
(d)Show that, in general, this worst-case total number of comparisons for a sorted list of n elements is n(n - 1) / 2, and state the resulting Big O time complexity.(3)
(e)State two different strategies for choosing the pivot that would make this particular worst-case scenario (an already-sorted list) far less likely to occur in practice.(2)
(Total for Question 6 is 12 marks)
7
A courier company's road network is modelled as a weighted graph. Vertices A to F represent depots, and edge weights represent journey times in minutes between directly connected depots:

Edges: A-B: 4, A-C: 2, B-C: 1, B-D: 5, C-D: 8, C-E: 10, D-E: 2, D-F: 6, E-F: 3

Dijkstra's algorithm is used to find the shortest journey time from depot A to every other depot.
(a)State one condition that all edge weights in a graph must satisfy for Dijkstra's algorithm to correctly find shortest paths.(1)
(b)Complete the table below to trace Dijkstra's algorithm starting from A. At each step, give the vertex settled and the current shortest known distance to each vertex (write "-" if a distance is not yet known). The first row is completed for you.
stepvertex settledABCDEF
1A042---
2
3
4
5
6
(5)
(c)State the shortest journey time from A to F, and give the corresponding path of depots visited.(2)
(d)Explain how the path found in part (c) can be reconstructed from the completed table, without the algorithm needing to store the whole path directly as it runs.(2)
(Total for Question 7 is 10 marks)
8
Dijkstra's algorithm can be implemented in different ways, giving different overall time complexities. Let V be the number of vertices and E the number of edges in the graph.
(a)State the overall time complexity of Dijkstra's algorithm when implemented using an adjacency matrix, where finding the next unvisited vertex with the smallest tentative distance requires scanning all V vertices, and this scan is repeated once for each of the V vertices settled.(2)
(b)State the overall time complexity of Dijkstra's algorithm when implemented using an adjacency list together with a min-heap (priority queue) to select the next vertex, where each of the E edges may cause one O(log V) update to the heap.(2)
(c)The courier network in the previous question has V = 6 vertices and E = 9 edges. Calculate the approximate number of operations each implementation from parts (a) and (b) would require.(4)
(d)State, with a reason, which implementation would be expected to show a clearer advantage as the size of the network grows very large, assuming the network stays sparse (E grows roughly in proportion to V, rather than to V2).(2)
(Total for Question 8 is 10 marks)
9
The same courier network from the previous two questions is now searched using the A* algorithm to find the shortest journey time from A to F. Straight-line distance estimates (heuristic values) to F are given below, and are known to be admissible (never greater than the true remaining journey time to F):

h(A) = 9, h(B) = 7, h(C) = 8, h(D) = 4, h(E) = 2, h(F) = 0

At each step, A* expands the vertex in the open list with the smallest value of f(vertex) = g(vertex) + h(vertex), where g(vertex) is the shortest distance found so far from A to that vertex.
(a)Calculate f(A) at the start of the search, given g(A) = 0.(1)
(b)A is expanded first. Calculate g, h and f for its neighbours B and C once A has been expanded.(2)
(c)Complete the table below to continue the A* trace, showing which vertex is expanded at each step and the resulting g and f values of any vertices whose distance is improved as a result. The first two steps are shown.
stepvertex expandedupdated vertices (g, f)
1AB: g=4, f=11 ; C: g=2, f=10
2CB: g=3, f=10 ; D: g=10, f=14 ; E: g=12, f=14
3
4
5
6
(4)
(d)State the total journey time and the path found by A* from A to F, and compare this result with the result obtained using Dijkstra's algorithm in the earlier question.(3)
(e)State the total number of vertices expanded by A* in this trace, and comment on whether this shows an efficiency advantage over Dijkstra's algorithm for this particular graph.(3)
(Total for Question 9 is 13 marks)
10
A satnav app calculates driving routes across a national road network containing millions of junctions.
(a)Discuss the relative advantages of using Dijkstra's algorithm compared with the A* algorithm for calculating a single driving route between two specific junctions in this network, and describe one situation in which Dijkstra's algorithm would still be the more appropriate choice.(8)
(Total for Question 10 is 8 marks)
11
An admissible heuristic h(v) for a search from vertex v to a goal G never overestimates the true shortest remaining distance from v to G, i.e. h(v) ≤ actualDistance(v, G) always. A consistent (monotone) heuristic additionally satisfies h(u) ≤ cost(u, v) + h(v) for every edge (u, v). A* is only guaranteed to find the shortest path when its heuristic is admissible.
(a)In the courier network used earlier in this paper, the true shortest remaining journey time from D to F is 5 minutes, and from E to F is 3 minutes. State, with a reason, whether the heuristic values h(D) = 4 and h(E) = 2 used earlier are each admissible.(2)
(b)Show that the heuristic values h(D) = 4 and h(E) = 2 satisfy the consistency condition for the edge D-E (weight 2).(2)
(c)A much simpler graph has three vertices: S (start), X, and G (goal), plus a fourth vertex Y. Edges: S-X weight 1, X-G weight 5, S-Y weight 1, Y-G weight 1. The true shortest distance from S to G is therefore 2 (via Y: S-Y-G), not 6 (via X: S-X-G). Suppose A* is run using the heuristic values h(X) = 0 and h(Y) = 10 (note: h(Y) = 10 is NOT admissible, since the true remaining distance from Y to G is only 1). Complete the trace below to show which vertex A* expands at each step, and state the path and total distance A* returns.
stepvertex expandedg, f of vertices reached
1SX: g=1, f=1 ; Y: g=1, f=11
2
3
(6)
(d)State what this example demonstrates about the importance of the admissibility condition for A* to guarantee an optimal (shortest) result.(1)
(Total for Question 11 is 11 marks)
12
A warehouse robot navigates a grid-shaped map with R rows and C columns of cells. Each cell is connected to its (up to 4) directly adjacent cells (up, down, left, right), forming a graph where each cell is a vertex.
(a)State, in terms of R and C, the number of vertices V in this graph.(1)
(b)Show that the number of edges E in this grid graph is given by E = R(C - 1) + C(R - 1).(2)
(c)The warehouse grid has R = 100 and C = 100 (a 100 x 100 grid). Calculate V and E for this grid.(3)
(d)Using the adjacency-list-with-min-heap implementation of Dijkstra/A*, with time complexity O((V + E) log V), calculate an estimate for the number of operations needed to find a route across this 100 x 100 grid. Give your answer to 3 significant figures.(3)
(e)In practice, A* with a well-chosen heuristic (such as Manhattan distance, |x1 - x2| + |y1 - y2|, between grid coordinates) typically explores far fewer than V vertices when finding a route between two specific cells, even though the algorithm's worst-case time complexity calculated in part (d) is the same as Dijkstra's. Explain why this is the case.(2)
(Total for Question 12 is 11 marks)
Mark scheme · A2.6 Advanced Algorithms: Searching, Sorting and Path-Finding

Question 1

Question 2

Question 3

Question 4

Question 5

Question 6

Question 7

Question 8

Question 9

Question 10

Question 11

Question 12

Mark your answers

This checks your answers in your browser, stores nothing on a server and needs no account.

Question 1

12 marks
Did your answer earn the marks?

Question 2

13 marks
Did your answer earn the marks?

Question 3

8 marks
Did your answer earn the marks?

Question 4

12 marks
Did your answer earn the marks?

Question 5

12 marks
Did your answer earn the marks?

Question 6

12 marks
Did your answer earn the marks?

Question 7

10 marks
Did your answer earn the marks?

Question 8

10 marks
Did your answer earn the marks?

Question 9

13 marks
Did your answer earn the marks?

Question 10

8 marks
Did your answer earn the marks?

Question 11

11 marks
Did your answer earn the marks?

Question 12

11 marks
Did your answer earn the marks?
Mark my answers