Binary Search

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Write a program to perform binary search

#include<stdio.h>
#include<conio.h>
void main()
{
int c,first,last,mid,n,el,array[50];
clrscr();
printf("eneter the number of element(max 50)\n");
scanf("%d",&n);
printf("enter the element in ascending order \n");
for(c=0; c<n; c++)
scanf("%d",&array[c]);
printf("enter value to find \n");
scanf("%d",&el);
first=0;
last=n-1;
mid=(first+last)/2;
while(first<=last)
{
if(el>array[mid])
first=mid+1;
else if(array[mid]==el)
{
printf("%d found at location %d \n",el,mid+1);
break;
}
else
last=mid-1;
mid=(first+last)/2;
}
if(first>last)

printf("search unsuccessful-element not found %d is not present in the list \


n",el);
getch();
}

You might also like