C PROGRAMMINGDATA STRUCTURES
binary search on array
Binary search on array
#include<stdio.h>
#include<conio.h>
main()
{
int array[20],size,search,loop;
int location,first,last,middle;
printf("Enter the size of arrayn");
scanf("%d",&size);
printf("Enter %d elements of array in sorted ordern",size);
for(loop=0;loop<size;loop++)
{
scanf("%d",&array[loop]);
}
printf("Enter the element of array to search n");
scanf("%d",&search);
first=0;
last=size-1;
middle=(first+last)/2;
while(first<=last)
{
if(search==array[middle])
{
printf("%d is found at location %d in arayn",search,middle+1);
break;
}
else if(search>array[middle])
{
first=middle+1;
}
else
{
last=middle-1;
}
middle=(first+last)/2;
}
getch();
}