advertisement

CS 5302 Data Structures and Algorithm Tutorial 2 Recursion (Suggested Solution) Programming Exercise 1. Suppose you are given an n-element array A containing distinct integers that are listed in increasing order. Given a number k, describe a recursive algorithm to find two integers in A that sum to k, if such a pair exists. What is the running time of your algorithm? Algorithm FindPair(A, i, j, k) Input An integer subarray A[i…j] and integer k Output Return true if there are two elements of A[i..j] that sum to k if i = j then return false else if A[i] + A[j] < k then return FindPair(A, i+1, j, k) else if A[i]+A[j] > k then return FindPair(A, i, j-1, k) else return true endif endif endif For each call, the running time is O(1). For each call, at most one recursive call is activated. Since the input size decrease by 1 at each recursive call, we can represent the running time as: T(n) = T(n-1) + O(1) Obviously, T(n) = O(n).