Home / Questions / Write C code to do Binary Search in an Array?
Explanatory Question

Write C code to do Binary Search in an Array?

👁 488 Views
📘 Detailed Answer
🕒 Easy to Read
Read the answer carefully and go through the related questions on the right side to improve your understanding of this topic.

Answer with Explanation


#include <stdio.h>
#include <conio.h>
void main()
{
int array[10];
int i, n, elem, found=0;
clrscr();
printf("Enter the value of N\n");
scanf("%d",&n);
printf("Enter the elements one by one\n");
for(i=0; i<n ; i++)
scanf("%d",&array[i]);
printf("Input array is\n");
for(i=0; i<n; i++)
printf("%d\n",array[i]);
printf("Enter the element to be searched\n");
scanf("%d", &elem);
/* Binary search begins */
l=0;
u=n-1;
While((l<u) && (found==0))
{
mid=(l+u)/2;
if(a[mid]==elem)
found=1;
else
if(a[mid]>elem)
u=mid-1;
else
l=mid+1;
}
mid=mid+1;
if ( found == 1)
printf("SUCCESSFUL SEARCH\n");
else
printf("Search is FAILED\n");
} /* End of main */