Best C Programing code for Binary Search using function (February,2021)

#include<stdio.h>

int binsear(int [],int,int);

int main()
{
    int ar[50],m,i,n,p;
    printf("\nEnter the number of elements : ");
    scanf("%d",&m);

    printf("\nEnter the values in ascending order : ");
    for(i=0;i<m;i++)
        scanf("%d",&ar[i]);
    printf("\nEnter the value you wanna search : ");
    scanf("%d",&n);
    if(binsear(ar,m,n))//1/non zero = true   0 = false
        printf("\nFound");
    else
        printf("\nNot Found");
}

int binsear(int ar[],int p,int q)
{
    int lb=0,ub=p-1,mid;

    while(lb<=ub)
    {
        mid=(lb+ub)/2;
        if(ar[mid]== q)
            return 1;
        else if(ar[mid]>q)
            ub=mid-1;
        else
            lb=mid+1;
    }
    return 0;
}

Leave a Reply