Binary Search Using Divide and Conquer

Algorithm(Pseudo Code)

BinarySearch(array,low,high,key)//where key is the element to be searched
{
     if(low==high)
    if(a[low]==key)
     return low;
     else
     return -1;
}
else{
    mid=(low+high)/2
    if(key==array[mid])
    return mid;
    else if(key>array[mid])
    return BinarySearch(array,mid+1,high,key)
    else
    return BinarySearch(array,low,mid+1,key)
}
}

Code

#include <stdio.h>
// int binarysearch(int,int,int,int);
void main(){
    int n,key;
    printf("ENTER THE NUMBER OF ELEMENTS:");
    scanf("%d",&n);
    int a[n];
    printf("ENTER THE ELEMENTS:");
    for(int i=0;i<n;i++){
    scanf("%d",&a[i]);
    }int low=0,high=n-1;
    printf("ENTER THE ELEMENT TO BE SEARCHED:");
    scanf("%d",&key);
    int flag=binarysearch(a,low,high,key);
    if(flag==-1)
    printf("Search Unsuccessful");
    else 
    printf("Search Successful, Element found at position :%d",flag);
}
int binarysearch(int *a,int low,int high,int key){
    if(low==high)
    {
        if(a[low]==key)
        return low;
        else
        return -1;

    }
    else 
    {
        int mid=low+(high-low)/2;
        if(key==a[mid])
        return mid;
        else if(key>a[mid])
        return binarysearch(a,mid+1,high,key);
        else
        return binarysearch(a,low,mid-1,key);
    }
}

Output

ENTER THE NUMBER OF ELEMENTS:5
ENTER THE ELEMENTS:1
2
3
4
5
ENTER THE ELEMENT TO BE SEARCHED:3
Search Successful, Element found at position :2

Leave a Comment

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