tags:

views:

85

answers:

4

The elements of the array are arranged in non-decreasing order. I need to search the array for a given element in the least possible time.

+2  A: 

Use binary search to find it.

nos
+2  A: 

Since the array is sorted you can make use of Binary Search.

A linear search will take O(n) time because it does not make use of the sorted property. But a binary search will take O(log n) time.

codaddict
Anything better than binary search. I mean in terms of time complexity
Nadeem
cant this be done in O(n) time
Nadeem
@Nadeem You can't do better than `O(log n)` here.
Andreas Brinck
binary search `O(log n)` which is better (faster) than `O(n)`.
codaddict
@Nadeem `O(log n)` is much faster than `O(n)`
Andreas Brinck
Got it ........
Nadeem
A: 

If all you know is that the array is sorted in non-decreasing order, you can't do better than binary search with its guaranteed O(log N) performance (as pointed out by other posters).

If you can assume a reasonably uniform distribution of numbers in the array, then interpolation search can give O(log log N) performance in the average case, which is better than binary search. (However, in the worst case - an array with exponential growth - it's O(N)).

Simon Nickerson
Inerpolation search?Well let me have a look at it.
Nadeem
A: 

Well, if you need better than Binary, you -could- use heuristics like Newton Search, which is a derivative of binary search, with moving split border - every time the value is greater, increase the step, if it's smaller, decrease it.

split = 0.5;
while(1)
{
    point = lower+split*(upper-lower);
    if(x>a[point])
    {
        lower = point;
        split*= 1.2
    }
    else if(x<a[point])

    {
        upper=point;
        split /=1.2
    } else break;
}

This supposedly yields better results with sets that have polynomial layouts and unbound sets. It gives worse results with random or linear layouts. This can also crash with split growing above 1 without proper safeguards.

SF.
Great to have a different answer !!!!
Nadeem