5

I'm working on a homework problem and I'm having some difficulties creating a O(n*logn) solution. I need to write a function that takes a pre-sorted array and a value to search for. I then need to find if any two elements of the array sum to equal that value.

I need to create both O(n) and O(n*logn) algorithms for this.

The O(n) was easy to create; however, I am having difficulties creating the O(n*logn) algorithm without adding in some gratuitous code that doesn't actually help in solving the problem. If anyone could give me some pointers on what I might be missing it would be appreciated.

1
  • 4
    @letsc: use two indexes a and b; initialize with a=1 and b=n. Check sum of elements at indexes a and b. If the sum is your target, stop, you found the elements. If the sum is lower, increase a; if it's lower, decrease b. When a=b, stop, there are no elements matching. Because the elements are sorted, you'll only skip pairs which you know aren't candidates. Commented Jul 4, 2012 at 14:30

2 Answers 2

4

Start at the first element, and go sequentially. While that, search for the second element using binary search.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I can't believe I missed that.
0

Because they are pre sorted you can use a binary search and a linear search

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.