Tweet

### Binary Search Using C Program

A sorted array is searched by Binary search.If the array is sorted , we can employ binary search , which brilliantly halves the size of the search space each time it examines one array element.Binary  means two , so it divides an array two halves for searching . This searching is applicable only to an ordered table ( in either ascending or in descending order ) .

Program code :

```#include<stdio.h>
#include<conio.h>
void binary_search(int [],int,int);
void main()
{
char ch;
int arr,v,size,i;
do{
clrscr();
printf("\t Enter array size : ");
scanf("%d",&size);

for(i=0;i<size;i++)
{
printf("\n\t Enter element :");
scanf("%d",&arr[i]);

}
printf("\n\t Search element :");
scanf("%d",&v);
binary_search(arr,v,size);
printf("\n\t Continue (y/n):");
ch=getch();

}while(ch=='y'||ch=='Y');
}

void binary_search(int arr[],int v,int size)
{
int found=0;
int high=size-1,low=0,mid;
mid=(high+low)/2;
printf("\n\t Looking for %d\n\t",v);
while((!found)&&(high>=low))
{
printf("Low:%d  Mid:%d  High:%d\n\t",low,mid,high);
if(v==arr[mid])
{
printf("Key value found at position %d",mid+1);
found=1;
}
else
{
if(v<arr[mid])
high=mid-1;
else
low=mid+1;
mid=(high+low)/2;
}
}

if(found==1)
printf("\n\t Search sucessful");
else
}
```

Output :