First time here? Checkout the FAQ!
x
menu search
brightness_auto
more_vert
Write a program to implement Binary Search on sorted set of integers.
thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike

1 Answer

more_vert
#include<stdio.h>
int n;
int binary(int a[],int n,int x)
{
 int low=0,high=n-1,mid;
 while(low<=high)
 {
 mid=(low+high)/2;
 if(x==a[mid])
 return(mid);

else if(x<a[mid])
 high=mid-1;
 else
 low=mid+1;
 }
 return(-1);
}
int main()
{
 int y,i,j;
 printf("enter the size of the array:");
 scanf("%d",&n);
 int a[n];
 printf("entered sorted list of array:");
 for(i=0;i<n;i++)
 {
 scanf("%d",&a[i]);
 }
 printf("enter the number to be searched:");
 scanf("%d",&y);
 j=binary(a,n,y);
 i=j;
 if(j==-1)

 printf("element not found");

else {
 printf("\n %d occurred at position=%d \n",y,i+1);
 }
 return 0;
}


 

image


thumb_up_off_alt 0 like thumb_down_off_alt 0 dislike
...