BINARY SEARCH PROGRAM IN C

//this code is designed by codenation.
//5:52 23/11/2020

#include<stdio.h>

int main()
{
    int N;
    
    printf("enter the size of data :\n");
    scanf("%d",&N);
    
    int data[N],i,item,mid,LOC,beg=0,end=N-1;
    
    printf("enter the data in sorted manner : \n");
    for(i=0;i<N;i++)
    {
        scanf("%d",&data[i]);
    }
    
    printf("enter the item to be searched :\n");
    scanf("%d",&item);
    
    mid=(int)(beg+end/2);
    while(beg<=end && data[mid]!=item)
    {
        if(item<data[mid])
        {
            end=mid-1;
        }
        else
        {
            beg=mid+1;
        }
        mid=(int)((beg+end)/2);
    }

    if(data[mid]==item)
    {
        LOC=mid;
    }
    else
    {
        LOC=-1;
    }
    
    if(LOC==mid)
    {
        printf("the item is at location %d",LOC+1);
    }
    else
    {
        printf("item is not present in an array.");
    }
}

//this code is developed by codenation.

Comments