Recursion and Advanced Algorithms - Worksheets, Questions and Revision

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

Download PDFJump to mark scheme (page 9)
« Previous: Object-Oriented ProgrammingNext: Elements of Computational Thinking »
Revision Library
revisionlibrary.co.uk
A-Level · AQA

A1.10 Recursion and Advanced Algorithms

AQA 7517 · Calculators not allowed · about 130 minutes
Total Marks
Name: _______________________________    Date: ____ / ____ / ______
Answer ALL questions. Show all your working.
1
A programmer writes the following recursive AQA pseudocode function to calculate the factorial of a non-negative integer n (where n! = n x (n-1) x (n-2) x ... x 1, and 0! is defined as 1).
FUNCTION Factorial(n)
   IF n = 0 THEN
      RETURN 1
   ELSE
      RETURN n * Factorial(n - 1)
   ENDIF
ENDFUNCTION
(a)State the base case of the function Factorial(n).(1)
(b)Complete a trace table showing the value of n passed to each recursive call made when evaluating Factorial(5), and the value each call returns, from the first call (n = 5) to the last.(5)
(c)State the value returned by the original call Factorial(5).(1)
(d)The function is instead called with a negative argument, Factorial(-3). Explain, with reference to the base case and the call stack, what would happen, and why this is a general risk when writing recursive functions.(3)
(Total for Question 1 is 10 marks)
2
A programmer named Aisha is writing a recursive function to add up the first n elements of an array called list (indexed from 0).
(a)Using AQA pseudocode conventions, write a recursive function SumList(list, n) that returns the sum of the first n elements of list (i.e. list[0] up to list[n-1]). Your function should return 0 if n = 0.(4)
(b)State the time complexity of SumList in Big O notation, in terms of n.(1)
(c)State the space complexity of SumList in Big O notation, giving a reason related to the call stack.(2)
(d)An iterative version of SumList uses a single WHILE loop and one accumulator variable instead of recursion. State one advantage of the iterative version over the recursive version for a very large array.(1)
(Total for Question 2 is 8 marks)
3
A games programmer called Rhys is writing a recursive backtracking function to find a path through a maze, represented as a 2D array grid, where grid[row][col] = 0 means an open cell and grid[row][col] = 1 means a wall. The array visited keeps track of cells already tried during the current search, and target holds the row and column of the exit cell. Two lines of the pseudocode, labelled ____(i)____ and ____(ii)____, have been removed.
FUNCTION SolveMaze(grid, row, col, target, visited)
   IF row < 0 OR row >= LEN(grid) OR col < 0 OR col >= LEN(grid[0]) THEN
      RETURN FALSE
   ENDIF
   IF grid[row][col] = 1 OR visited[row][col] = TRUE THEN
      RETURN FALSE
   ENDIF
   IF row = target[0] AND col = target[1] THEN
      RETURN TRUE
   ENDIF
   ____(i)____
   IF SolveMaze(grid, row + 1, col, target, visited) = TRUE THEN
      RETURN TRUE
   ENDIF
   IF SolveMaze(grid, row - 1, col, target, visited) = TRUE THEN
      RETURN TRUE
   ENDIF
   IF SolveMaze(grid, row, col + 1, target, visited) = TRUE THEN
      RETURN TRUE
   ENDIF
   IF SolveMaze(grid, row, col - 1, target, visited) = TRUE THEN
      RETURN TRUE
   ENDIF
   ____(ii)____
   RETURN FALSE
ENDFUNCTION
(a)State the missing pseudocode for the lines labelled ____(i)____ and ____(ii)____.(2)
(b)State the purpose of the visited array in this algorithm.(1)
(c)Explain why line ____(ii)____ (resetting visited[row][col] back to FALSE) is essential for the algorithm to correctly explore every possible path through the maze, rather than just the first path it happens to try.(2)
(d)State what the original call to SolveMaze returns if no path exists between the start cell and the target, and explain, with reference to the recursive calls, how the algorithm reaches this result.(3)
(Total for Question 3 is 8 marks)
4
The following recursive AQA pseudocode function calculates the nth Fibonacci number, where Fib(0) = 0, Fib(1) = 1, and Fib(n) = Fib(n-1) + Fib(n-2) for n ≥ 2.
FUNCTION Fib(n)
   IF n <= 1 THEN
      RETURN n
   ELSE
      RETURN Fib(n - 1) + Fib(n - 2)
   ENDIF
ENDFUNCTION
(a)Describe the tree of recursive calls made when evaluating Fib(4) (state which calls each call makes), and state the value returned.(3)
(b)For the larger call Fib(5), state the total number of function calls made in total (including the initial call to Fib(5) itself), and state how many of these calls are calls to the base case Fib(1).(3)
(c)Explain why the time complexity of Fib(n), as written above, is exponential, O(2n), and explain how storing previously computed results in a lookup array (memoisation) improves this.(3)
(d)Using AQA pseudocode conventions, write a memoised version FibMemo(n, memo), where memo is an array, indexed from 0, with every element initially set to -1 to indicate that value has not yet been calculated.(3)
(Total for Question 4 is 12 marks)
5
An array called catalogue, indexed from 0, holds 10 sorted reference numbers:

catalogue = [2, 5, 8, 12, 16, 23, 38, 45, 56, 72] (indices 0 to 9)

A recursive binary search function is written as follows.
FUNCTION BinarySearch(list, target, low, high)
   IF low > high THEN
      RETURN -1
   ENDIF
   mid <- (low + high) DIV 2
   IF list[mid] = target THEN
      RETURN mid
   ELSE
      IF list[mid] < target THEN
         RETURN BinarySearch(list, target, mid + 1, high)
      ELSE
         RETURN BinarySearch(list, target, low, mid - 1)
      ENDIF
   ENDIF
ENDFUNCTION
(a)State one precondition that must hold for the array catalogue before binary search can be used on it correctly.(1)
(b)Complete a trace table for the call BinarySearch(catalogue, 23, 0, 9), showing the values of low, high, mid and list[mid] for each recursive call made, until the target is found.(5)
(c)State the value returned by the original call, and the total number of recursive calls made (including the first call).(2)
(d)State the time complexity of binary search in Big O notation, and explain why doubling the number of elements in a sorted array only adds, at most, one extra comparison to a binary search of it.(2)
(Total for Question 5 is 10 marks)
6
Merge sort is a recursive, divide-and-conquer sorting algorithm. It is applied to the list [8, 3, 5, 1, 9, 2].
(a)State the two main phases of the merge sort algorithm.(2)
(b)State the two sub-lists produced when [8, 3, 5, 1, 9, 2] is first split in half.(2)
(c)The sub-list [8, 3, 5] is recursively split down into single-element lists ([8], [3] and [5]) and then merged back together. State the result of merging [3] and [5] first, and then state the result of merging [8] with that result.(2)
(d)By the same process, [1, 9, 2] merges down to [1, 2, 9]. State the fully sorted list produced when [3, 5, 8] and [1, 2, 9] are finally merged together, and state the worst-case time complexity of merge sort in Big O notation.(2)
(e)State one disadvantage of merge sort compared with an in-place sorting algorithm such as insertion sort.(1)
(Total for Question 6 is 9 marks)
7
The list [5, 2, 8, 1, 9, 3] is sorted using quicksort, using the Lomuto partition scheme with the last element of the (sub-)list always chosen as the pivot.
(a)State the pivot used for the first partition step.(1)
(b)Show the list after the first partition step is complete (elements less than the pivot moved before it, elements greater than or equal to the pivot moved after it, and the pivot placed in its final, correctly sorted position).(3)
(c)State the two sub-lists that quicksort will now be called on recursively.(2)
(d)State the best-case and worst-case time complexity of quicksort in Big O notation, and describe the input list that causes the worst case when the pivot is always chosen as the last element.(3)
(Total for Question 7 is 9 marks)
8
In the Towers of Hanoi puzzle, n disks of different sizes are stacked on a source peg, and must all be moved to a destination peg, using a third, spare peg, following two rules: only one disk may be moved at a time, and a larger disk may never be placed on top of a smaller one.
(a)State the recursive rule used to move n disks (n > 0) from a source peg to a destination peg, using a spare peg, and state the base case for n = 0.(3)
(b)Using AQA pseudocode conventions, write a recursive procedure Hanoi(n, source, destination, spare) that outputs the sequence of moves needed.(4)
(c)State the formula for the minimum number of moves needed to solve the puzzle with n disks, and use it to calculate the number of moves needed for 5 disks.(2)
(d)State the time complexity of the Hanoi procedure in Big O notation, in terms of n, and explain why.(2)
(Total for Question 8 is 11 marks)
9
Discuss the advantages and disadvantages of solving a problem using a recursive algorithm rather than an equivalent iterative algorithm. Your answer should consider readability, memory use and performance, and should refer to specific examples of problems for which one approach is generally preferred over the other.
(Total for Question 9 is 6 marks)
10
A graph is stored as an adjacency list, where each vertex lists its directly connected neighbours in alphabetical order:

A: [B, C]
B: [A, D, E]
C: [A, F]
D: [B]
E: [B, F]
F: [C, E]

A recursive depth-first search (DFS) is implemented as follows.
PROCEDURE DFS(graph, vertex, visited)
   visited[vertex] <- TRUE
   OUTPUT vertex
   FOR EACH neighbour IN graph[vertex]
      IF visited[neighbour] = FALSE THEN
         CALL DFS(graph, neighbour, visited)
      ENDIF
   ENDFOR
ENDPROCEDURE
(a)State the data structure that recursive DFS implicitly uses to keep track of which vertices to return to, and name the equivalent explicit data structure that an iterative version of DFS would need to manage this itself.(2)
(b)Using the pseudocode and the adjacency list given, and assuming neighbours are always considered in the alphabetical order shown, state the order in which the vertices are visited (output) when CALL DFS(graph, A, visited) is made, with every vertex initially unvisited.(4)
(c)Explain why DFS is not guaranteed to find the shortest path (fewest edges) between two vertices in an unweighted graph, and name an alternative graph traversal algorithm that would guarantee this.(2)
(Total for Question 10 is 8 marks)
11
A binary search tree stores nodes with a value, a left child pointer and a right child pointer (NULL if there is no child). The tree used in this question has the following structure:

Root: 50
50's left child: 30, 50's right child: 70
30's left child: 20, 30's right child: 40
70's left child: 60, 70's right child: 80
(20, 40, 60 and 80 are all leaves, with no children)

The following recursive procedure is defined.
PROCEDURE InOrder(node)
   IF node <> NULL THEN
      CALL InOrder(node.left)
      OUTPUT node.value
      CALL InOrder(node.right)
   ENDIF
ENDPROCEDURE
(a)State the standard name given to the tree traversal implemented by this pseudocode, in terms of the order in which a node's left subtree, the node itself, and its right subtree are processed.(1)
(b)State the full sequence of values output when CALL InOrder(root) is made on the tree described above.(1)
(c)Complete a trace table showing, in order, the node value passed to each call InOrder(node) made on a node that actually holds a value (i.e. exclude any call made where node = NULL, which returns immediately), listing the order in which these calls are first entered.(4)
(d)The order of calls found in part (c) is identical to a different, standard tree traversal order. Identify this traversal, and justify your answer by referring to when a node's own value would be processed relative to its child subtrees in that traversal.(2)
(Total for Question 11 is 8 marks)
12
Time complexities are often compared using Big O notation to describe how an algorithm's running time grows as the size of its input, n, increases.
(a)State the following time complexities in order, from the most efficient (slowest growing) to the least efficient (fastest growing), as n becomes very large: O(n), O(log n), O(n2), O(1), O(n log n), O(2n).(3)
(b)An algorithm has time complexity O(n2). When n = 100, it takes approximately 50 milliseconds to run on a particular computer. Assuming the same constant of proportionality, calculate an estimate for how long the same algorithm would take to run on the same computer when n = 400. Show your working.(3)
(c)A different algorithm, solving the same underlying problem, has time complexity O(n log n) instead. State, with a reason, which of the two algorithms (the O(n2) one from part (b), or this O(n log n) one) would be preferred for very large values of n.(2)
(Total for Question 12 is 8 marks)
Mark scheme · A1.10 Recursion and Advanced Algorithms

Question 1

Question 2

Question 3

Question 4

Question 5

Question 6

Question 7

Question 8

Question 9

Question 10

Question 11

Question 12