2
$\begingroup$

I have an algorithm which searches a sorted int array for two elements which sum up to a searched value. First I thought that the complexity is $\mathcal{O}(n),ドル but the interpolation search algorithm has a similar approach and has a $\mathcal{O}(\log(log(n)))$ complexity with uniform distributed elements.

Which is the right complexity and why?

boolean hasPairWithSum(int[] elements, int sum) {
 int start = 0;
 int end = elements.length-1;
 while (start < end) {
 int tempSum = elements[start] + elements[end];
 if (tempSum == sum) return true;
 if (tempSum > sum) {
 end--;
 } else {
 start++;
 }
 }
 return false;
}
Raphael
73.3k31 gold badges183 silver badges403 bronze badges
asked Oct 11, 2017 at 20:49
$\endgroup$
2
  • $\begingroup$ O(log log n) ⊊ O(n) $\endgroup$ Commented Oct 11, 2017 at 21:22
  • 2
    $\begingroup$ You may want to try a structured approach. $\endgroup$ Commented Oct 11, 2017 at 21:23

1 Answer 1

0
$\begingroup$

This method works in linear time, because end - start decreases by 1 on each iteration. It's $n - 1$ initially, hence the loop will make at most $n - 1$ iterations.

answered Oct 11, 2017 at 21:09
$\endgroup$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.