Binary_Search

Simple Binary Search 

The my_binary function will find the value named key and check if the key value is in the array list or not.The function will return -1 if the key value is not in the array list else it will return the position of the element in the array list

int my_binary(int ara[], int lo, int hi, int key, int siz)
{
    if(hi>=lo)
    {
        int mid = lo + (hi-lo)/2;
        if(ara[mid]==key)
            return mid;
        if(key>ara[mid])
            return my_binary(ara,mid+1,hi,key,siz);
        else
            return my_binary(ara,lo,mid-1,key,siz);
    }
    return -1;      
}


int my_lower_binary(int ara[], int lo, int hi, int key, int siz)
{
    if(hi>=lo)
    {
        int mid = lo + (hi-lo)/2;
        if((mid==0 || key>ara[mid-1]) && ara[mid]==key)
            return mid;
        else if(key>ara[mid])
            return my_lower_binary(ara,mid+1,hi,key,siz);
        else
            return my_lower_binary(ara,lo,mid-1,key,siz);
    }
    return -1;
}

int my_upper_binary(int ara[], int lo, int hi, int key, int siz)
{
    if(hi>=lo)
    {
        int mid = lo + (hi-lo)/2;
        if((mid==siz-1 || key<ara[mid+1]) && ara[mid]==key)
            return mid;
        else if(key<ara[mid])
            return my_upper_binary(ara,lo,mid-1,key,siz);
        else
            return my_upper_binary(ara,mid+1,hi,key,siz);
    }
    return -1;
}

মন্তব্যসমূহ