Question

Given an array A[1..n] of positive integers and given a number x, find if any two...

Given an array A[1..n] of positive integers and given a number x, find if
any two numbers in this array sum upto x. That is, are there i,j such
that A[i]+A[j] = x? Give an O(nlogn) algorithm for this. Suppose now
that A was already sorted, can you obtain O(n) algorithm?

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

Algorithm in O(nlogn) time for A[i]+A[j] = x:

findpair(A[] ,x)

1. sort Array A by using haep sort . it wiil have O(nlogn) complexity.

2, set low=0

3, set high= arr.size-1

4. while(low <high)

        If (A[low] + A[high] == x)  then return 1

Else if ( A[low] + A[high] < x ) then low++

Else high++

End IF

end while

5. end function

============================================================================================

This algorithm has complexity of O(mlogn+n) =O(nlogn)

============================================================================================

. Suppose now that A was already sorted, can you obtain O(n) algorithm?

Ans: yes as A is already sorted. There will be only a while loop as shown in the algorithm above. so it will the complexity of On).

Add a comment
Know the answer?
Add Answer to:
Given an array A[1..n] of positive integers and given a number x, find if any two...
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