In: Computer Science
Question 3:
You are requested to design an algorithm to check whether a key pair (sum of two numbers only) exist in a given array (of size N) or not. If the key pair exists at least once then the algorithm should return “True”; otherwise “False”.
For example, given an array A[8, -3, 9, 5, -3, 11, 2, -7, 4, 11] where the key pair is 13, then the required algorithm should return “True” because such pair exist at least once ex:(9+4). Another example, given the same array, where the key pair is 21, the required algorithm should return “false”, as there is no any pair with sum equal to 21
iii. What is the complexity of this algorithm in the best and worst case? (5 marks
Find the solution to the above question below, do read all the steps provided carefully and in case of any comments do comment below. If found helpful please upvote this.
Algorithm
Code
A = [8, -3, 9, 5, -3, 11, 2, -7, 4, 11]
Sort(A)
a = 0
b = n-1
sum = 19
while a < b:
if A[a]+A[b] == sum:
return True
if A[a]+A[b] < sum:
a = a+1
else:
b = b-1
return False
Screenshot of code
Part ii
In order to get a better performance merge sort should be used, merge sort has worst case time complexity of O(nlog(n)) which is better than any other sorting algorithm
Part iii
Sorting will take nlog(n) time in any case
Now for best case finding the pair will take O(1) so overall it will be O(nlog(n))
In worst case findign teh pair will take O(n/2) so overall it will O(nlog(n)) + O(n/2) which is same as O(nlog(n))