Solved programming problem

Binary Search With Recursion in C.

Source code

NB- This Code Only works when all array element are sorted 

#include<stdio.h>

int  binary_search(int array[],int m,int first,int last)

{

    int mid = (first + last)/2;

    int flag=0;

    if(array[mid]==m) ///if found

    {

        flag=1;

        return flag;

    }

    else if(first>=last) ///base case

    {

        flag=0;

        return flag;

    }

    else if(array[mid]>m)

    {

        first = mid+1;

        return  binary_search(array,m,first,last); ///call the function

    }

    else if(array[mid]<m)

    {

        last = mid -1;

        return binary_search(array,m,first,last); ///call the function

    }

}

int main()

{

    int array[100],n,last,first,i,m;

    printf("Enter Your Array Size: ");

    scanf("%d",&n);

    printf("Please Enter Array Element: ");

    for(i=0; i<n; i++)

    {

        scanf("%d",&array[i]);

    }

    printf("Please Enter Which Element You Want to Search: ");

    scanf("%d",&m);

    first=0;

    last =n-1;

    int flag=binary_search(array,m,first,last);

    if(flag==1)

    {

        printf("
Found
");

    }

    else

    {

        printf("
Not Found
");

    }

   return 0;

}

Output

Enter Your Array Size: 5
Please Enter Array Element: 5 4 3 2  1
Please Enter Which Element You Want to Search: 3

Found

Join the discussion

Add your comment