In Progress
Lesson 15 of 43
In Progress

# Binary Search

##### Akash

Let ai, 1<= i <= n, be a list of elements that are sorted in non decreasing order. Consider the problem of determining whether a given element x is present in the list.If x is present,we are to determine a value j such that aj = x. If x is not in the list, then j is to be set to zero. Let P = (n,ai,…, al,x) denote an arbitrary instance of this search problem(n is the number of elements in the list ai,…, al is the list of elements,and x is the element searched for)

In this example,any given problem P gets divided (reduced)into one new subproblem. This division takes only theta(1) time. After a comparison with aq, the instance remaining to be solved (if any) can be solved by using this divide-and-conquer scheme again.If q is always chosen such that aq is the middle element(that is,q = [(n +l)/2)], then the resulting search algorithm is known as binary search.Note that the answer to the new subproblem is also the answer to the original problem P; there is no need for any combining. Algorithm 2 describes this binary search method, where BinSrch has four inputs a[], i, l and x. It is initially invoked as BinSrch(a,l,n,x).

A non recursive version of BinSrch is given in Algorithm 3. Bin Search has three inputs a,n,and x. The while loop continues processing as long as there are more elements left to check.At the conclusion of the procedure 0 is returned if x is not present, or j is returned, such that a[j] = x.

Is BinSearch an algorithm? We must be sure that all of the operations such as comparisons between x and a[mid] are well defined. The relational operators carry out the comparisons among elements of a correctly if these operators are appropriately defined. Does BinSearch terminate? We observe that low and high are integer variables such that each time through the loop either x is found or low is increased by at least one or high is decreased by at least one.Thus we have two sequences of integers approaching each other and eventually low becomes greater than high and causes termination in a finite number of steps if x is not present.