A binary search algorithm (or binary chop) is a technique for finding a particular value in a linear array, by ruling out half of the data at each step, widely but not exclusively used in computer science.
A binary search finds the median, makes a comparison to determine whether the desired value comes before or after it, and then searches the remaining half in the same manner. Another explanation would be: Search a sorted array by repeatedly dividing the search interval in half. Begin with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, narrow the interval to the lower half. Otherwise narrow it to the upper half.
Its running time is O(logn).
#include
using namespace std;
//Divide and conquer strategy - Binary Search
/*This algorithm is the simplest application of divide and conquer.
It finds a particular value in a linear array by ruling out half
of the data at each step.A binary search finds the median, makes
a comparision to determine whether the desired value comes before or
after it, and then searches the remaining half in the same manner.
However, the binary search algorithm applies only to sorted arrays.*/
int sorted_array[100];
int i=0;
int binary_search(int target)
{
int first = 0;
int last = i-1;
int mid;
while(first<=last) //while we haven’t reached the end of
{
mid = (first+last)/2; //rule out half of the data by spliting the array
if(sorted_array[mid]==target) //if we have found the target
return mid;
else if(sorted_array[mid]>target)
last = mid-1; //the desired value is in the lower part of the array
else
first = mid+1;//the desired value is in the upper part of the array
}
return -1; //there is no such element in the array
}
int main()
{
int j, n;
while(cin>>j)
sorted_array[i++]=j;
while(cin>>n) //search for an element n in the array
{
int result = binary_search(n); //position of the element n in the array
printf("%d",result);
}
}
10/08/2007
What is a Binary seach algorithm and how does it work?
at 7:04 AM Posted by algorithm
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment