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

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

CS3230 Tutorial 3 Q2. Given an array A of integers and a number k , give an eﬃcient 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 modiﬁcation of the partition algorithm done in class. Show that it works correctly. Partition(

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

View Full Document
This is the end of the preview. Sign up to access the rest of the document.

## This note was uploaded on 01/06/2012 for the course CS 3230 taught by Professor Sanjay during the Fall '10 term at National University of Singapore.

### 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
Ask a homework question - tutors are online