Saturday, 28 October 2017

Binary Search 


Let's understand without going into the details.
Let's say we have a sorted array, say in ascending order like:
1, 4, 10, 13, 40, 65, 100.

Now let's say I searched for 10. The program will execute and it will look at the middle term and will compare it with our number. If the match is found then it will show the position of array. And if it is smaller than the middle term then it will look for the numbers before the middle term, and this will go on until the number is found. If not found, then we will display: "Not found".

Program:


void main()
{
clrscr();
int n, i, arr[20], search, first, last, middle;
cout<<"Enter total number of elements :";
cin>>n;
cout<<"Enter "<<n<<" number :";
for (i=0; i<n; i++)
{
cin>>arr[i];
}
cout<<"Enter a number to find :";
cin>>search;
first = 0;
last = n-1;
middle = (first+last)/2;
while (first <= last)
{
if(arr[middle] < search)
{
first = middle + 1;

}
else if(arr[middle] == search)
{
cout<<search<<" found at location "<<middle+1<<"\n";
break;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
cout<<"Not found! "<<search<<" is not present in the list.";
}
getch();
}

No comments:

Post a Comment