Data Structure Binary Search

Program on Binary Search given below:

//Binary Searching
//In binary searching array should be monotonic

#include<stdio.h>
int binarysearch(int a[],int n,int data)
{
    int mid,l=0;
    int r=n-1;
    while(l<r)
    {
        mid = (l+r)/2;
        if(data == a[mid])
            return mid;
        else if(data < a[mid])
            r=mid-1;
        else
            l=mid +1;
    }
    return -1;
}
int main()
{
    int a[100],n,data;
    printf("enter the size of array");
    scanf(" %d",&n);
    printf("enter the array");
     for(int i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
    printf("enter the data to search");
    scanf("%d",&data);
    int S = binarysearch(a,n,data);
    if(S == -1)
    {
        printf(" Data not found");
    }
    else
    {
        printf(" Data is at index no. : %d",S);
    }
}

Output

enter the size of array 7
enter the array12 34 54 76 82 86 98
enter the data to search76

Leave a Reply

Your email address will not be published. Required fields are marked *

Solverwp- WordPress Theme and Plugin