Program to implement Binary Search

/* Binary Search */

/* Condition: List must be sorted order

and search the value at mid location of the list */

/* here a[100] – storage of array value

f,l,m    – first, last, mid position of array

x        – search value

i        – index variable

flag     – determine the value found or not found

*/

 

#include<stdio.h>

#include<conio.h>

void main()

{

int a[100],i,n,x,f,l,m,flag=0;

clrscr();

printf(“enter how many value in array\n”);

scanf(“%d”,&n);

printf(“Enter %d value in ascending order\n”,n);

for(i=0;i<n;i++)

scanf(“%d”,&a[i]);

printf(“Which value to be search ->”);

scanf(“%d”,&x);

/* Binary Search logic */

f=0;l=n-1;

while(f<=l)

{

m=(f+l)/2;

if(x==a[m])

{

flag=1;

break;

}

else if(x<a[m])

l=m-1;

else

f=m+1;

}

if(flag==0)

printf(“%d value not found\n”,x);

else

printf(“%d value found at location %d\n”,x,m);

getch();

}

 

resume

Mohit Arora
Follow me