Given an integer sorted array (sorted in increasing order) and an element x, find the x in given array using binary search. Return the index of x.

TITLE:-Binary Search (Recursive)

PROBLEM:-Given an integer sorted array (sorted in increasing order) and an element x, find the x in given array using binary search. Return the index of x.

Return -1 if x is not present in the given array.
Note : If given array size is even, take first mid.

Input format :

Line 1 : Array size

Line 2 : Array elements (separated by space)

Line 3 : x (element to be searched)

Sample Input :
6
2 3 4 5 6 8 
5 
Sample Output:
3 

SOLUTION:-

#include <iostream>
using namespace std;
// input - input array
// size - length of input array
// element - value to be searched
int bsearch(int first,int last,int input[],int element)
{
    
    int mid=(first+last)/2;
     if(first==mid||last==mid)
        return -1;
    if(input[mid]==element)
        return mid;
    else if(input[first]==element)
        return first;
    else if(input[last]==element)
        return last;
    else if(input[mid]<element)
    {
        first=mid+1;
        bsearch(first,last,input,element);
    }
    else{
        last=mid-1;
        bsearch(first,last,input,element);
    }
     
    
    
}
int binarySearch(int input[], int size, int element) {
    // Write your code here
    int first=0;
    int last=size-1;
    return bsearch(first,last,input,element);
}


int main() {
    int input[100000],length,element, ans;
    cin >> length;
    for(int i =0;i<length;i++)
    { 
        cin >> input[i];;
    }

    cin>>element;
    ans = binarySearch(input, length, element);
    cout<< ans << endl;
}

Similar Posts

Leave a Reply

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