t3ans - CS3230 Tutorial 3 Q2. Given an array A of integers...

Info iconThis preview shows pages 1–2. Sign up to view the full content.

View Full Document Right Arrow Icon
CS3230 Tutorial 3 Q2. Given an array A of integers and a number k , give an efficient algorithm to decide if there exist two elements A [ i ] and A [ j ], i 6 = j , such that A [ i ] + A [ j ] = k . Give time complexity bound of your algorithm. Ans: (A) Sort the array (takes O ( n log n ) time). (B) For each j , use binary search to check if the array contains the element k - A [ j ] (as A [ i ], with i 6 = j ). Time complexity: O ( n log n ) for step (A) above. O (log n ) for each j in step (B), and thus O ( n log n ) for step (B). Alternatively, a better way to do step (B) is as follows: Suppose array A [1 : n ] is sorted. i = 1; j = n . While i < j do { If A [ i ] + A [ j ] = k , then output yes. Else If A [ i ] + A [ j ] < k , then i = i + 1. Else If A [ i ] + A [ j ] > k , then j = j - 1. } The above will do step (B) in O ( n ) time. However, the overall complexity of steps (A) and (B) still remains O ( n log n ). Q3. Consider the following modification of the partition algorithm done in class. Show that it works correctly. Partition(
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
Image of page 2
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 3

t3ans - CS3230 Tutorial 3 Q2. Given an array A of integers...

This preview shows document pages 1 - 2. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online