BINARY SEARCH ALGORITHM

BINARY SEARCH ALGORITHM

In the Binary search, the condition is that the elements of the array should be in sorted order. then we find the mid value of the elements and then compare the el ement by the mid value. The following is the algorithm to binary search.

(BINARY SEARCH) BINARY (a, 0, n-1, num )

Here a is a sorted array with lower bound 0 and up per bound n-1 and num is a given element. The variable low, high a nd mid denote the beginning and middle location respectively. This algorithm finds the location num in a or sets flat to 0.

  1. Initialize the variable.

Set low=0, high=n-1 and mid= (beg + high/2), flag=1  

     2.Repeat steps 3 and 4 while low<=high

3.If num<a[mid] then

Set high=mid-1

Else

If num>a [mid] then

  Low=mid+1

Else if num==a[mid] then

Print “element found at location num”

Set flag=0

[end of if statement]

[end of if statement]

4.If flag=1

Print “search unsuccessful”.

5. Exit. 

C++ CODE

#include<iostream.h>
main()
{
int a[6]={2,5,8,9,10,12};
int low=0,high=5,mid,flag=1,n;
cout<<”Enter the item to be searched”;
cin>>n;
while(low<=high)
{
mid=(low+high)/2;
if(n<a[mid])
{
high=mid-1;
}
else if(n>a[mid])
{
low=mid+1;
}
else if(n==a[mid]) .ads in wordpress
{
cout<<endl<<”the item is found at location”<<mid;
flag=0;
break;
}
}
if(flag==1)
{
cout<<endl<<”Search unsuccessful”;
}
}

C CODE

#include<stdio.h>
main()
{
int a[6]={2,5,8,9,10,12};
int low=0,high=5,mid,flag=1,n;
printf(“Enter the item to be searched”);
scanf(“%d”,&n);
while(low<=high)
{
mid=(low+high)/2;
if(n<a[mid])
{
high=mid-1;
}
else if(n>a[mid])
{
low=mid+1;
}
else if(n==a[mid])
{
printf(“\nthe item is found at location %d”,mid);
flag=0;
break;
}
}
if(flag==1)
{
printf(“\nSearch unsuccessful”);
}
}

One Response to BINARY SEARCH ALGORITHM

  1. Very interesting info !Perfect just what I was searching for! “It’s not the having, its the getting.” by Elizabeth Taylor. cheap isabel marant sneakers

Leave a Reply

Your email address will not be published. Required fields are marked *


eight − 2 =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>