Monday, June 28, 2010

Binary search Implementation without Recursion

The features are
  • The following code does the binary search without recursion
  • We know that the time complexity for the binary search is O(logN)
  • It is efficient method for searching an element in a sorted array.
Code :(In C)

In its simplest form, binary search is used to quickly find a value in a sorted sequence (consider a sequence an ordinary array for now). We'll call the sought value the target value for clarity. Binary search maintains a contiguous subsequence of the starting sequence where the target value is surely located. This is called the search space. The search space is initially the entire sequence. At each step, the algorithm compares the median value in the search space to the target value. Based on the comparison and because the sequence is sorted, it can then eliminate half of the search space. By doing this repeatedly, it will eventually be left with a search space consisting of a single element, the target value.

5 comments:

Unknown said...

The code is not clear.
What is the value of x in this??
In if condition some part is missing..
Thanks in Advance

Dhinakaran said...

x is the value that you are searching and i will post the updated code .

Unknown said...
This comment has been removed by the author.
Unknown said...

a is array, x is value to be searched for, and n is length of array.

Nice blog. Appreciate it.

If any one intrested in C Graphics programs, please visit www.ncooltips.com

Unknown said...

This code needs update, as it fails for right boundary case.