Write C code to do Binary Search in an Array?

Data Structure >   Searching >   Binary Search  

Long Question

487


Answer:


#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 */


This Particular section is dedicated to Question & Answer only. If you want learn more about Data Structure. Then you can visit below links to get more depth on this subject.




Join Our telegram group to ask Questions

Click below button to join our groups.