Best C Programming code for Binary Search using pointer(February,2021)

#include<stdio.h>

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

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

int binsear(int *ptr,int p,int q)
{
    int lb=0,ub=p-1,mid;

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

int bubble(int *ptr,int m)
{
    int i,j,temp;
    for(i=0;i<m;i++)
    {
        for(j=0;j<m-i-1;j++)
        {
            if(*(ptr+j)>*(ptr+j+1))//if(ar[j]>ar[j+1])
            {
                temp=*(ptr+j);   //temp=ar[j];
                *(ptr+j)=*(ptr+j+1);   //ar[j]=ar[j+1]
                *(ptr+j+1)=temp;   //ar[j+1]=temp
            }
        }
    }
}

Leave a Reply