Thursday, 25 January 2018

BINARY-SEARCH 'C' PROGRAMMING

Output :

Enter the no.of  elements:5
Enter the 5 numbers:1 5 8 6 3
Enter number to be searched:8

Number Found

Enter the no.of  elements:5
Enter the 5 numbers:1 5 8 6 3
Enter number to be searched:9
Number Not Found

Code for Binary Search:

#include<stdio.h>
#include<stdlib.h>
int main ()
{
int *a;
int x,n,i=0,temp=0;
int mid=0,lowerb=0,upperb=0;
printf("enter the no.of  elements:");
scanf("%d",&n);
a=malloc(sizeof(int)*n);
printf("enter the %d numbers:",n);
for(i=0;i<n;i++)
{
    scanf("%d",&a[i]);
}
printf("enter number to be searched:");
scanf("%d",&x);
lowerb=0;upperb=n-1;
while(lowerb<=upperb)
{ mid=lowerb+((upperb-lowerb)/2);
    if(a[mid]==x)
    {temp++;
      printf("number found");
      break;
    }
    else if(a[mid]>x)
    {
        upperb=mid-1;
    }
    else
    {   lowerb=mid+1;

    }
}
if(temp==0)
{
    printf("number not found");
}


}

No comments:

Post a Comment

we are hear to discuss your queries ,so please feel free to ask any of your queries.

Wikipedia

Search results