Question

Given as input an array A of n positive integers and another positive integer x, describe an O(nlogn)-time algorithm that determines whether or not there exist two elements Ai and AONn the array A such that is exactly x.

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Hey,

Note: Brother in case of any queries, just comment in box I would be very happy to assist all your queries

hasArrayTwoCandidates (A[], ar_size, sum)
1) Sort the array in non-decreasing order.
2) Initialize two index variables to find the candidate 
   elements in the sorted array.
       (a) Initialize first to the leftmost index: l = 0
       (b) Initialize second  the rightmost index:  r = ar_size-1
3) Loop while l < r.
       (a) If (A[l]/A[r] == sum)  then return 1
       (b) Else if( A[l]/A[r] <  sum )  then l++
       (c) Else r--    
4) No candidates in whole array - return 0

Total time complexity will be O(nlog(n)) since sorting is the expensive here which takes nlogn time.

Kindly revert for any queries

Thanks.

Add a comment
Know the answer?
Add Answer to:
Given as input an array A of n positive integers and another positive integer x, describe...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT