pranay_teja
1/16/2018 - 8:01 PM

Binary search in array

#include <bits/stdc++.h>
using namespace std;

// #Searching #Theory
// Binary search works only for sorted arrays

int BinarySearch(vector<int> a, int l,int r, int x){
    if(l<=r){    // Base case: size>0 or l<=r (atleast 1 element to search)
        int m=l+((r-l)/2);  // mid index
        if(a[m]==x){
            return m;
        }else if(a[m]>x){
            return BinarySearch(a,l,m-1,x); // Search left 
        }else{
            return BinarySearch(a,m+1,r,x); // Search right
        }
    }
    return -1;  // if found no where return -1;
    
}

int main() {
	int t;
	cin>>t;
	while(t--){
	    int n;
	    cin>>n; // array size
	    vector<int> a(n);
	    for(int i=0;i<n;i++){
	        cin>>a[i];
	    }
	    int x;
	    cin>>x; // element to be searched
	    int i=BinarySearch(a,0,n-1,x);
	    if(i==-1){
	        cout<<x<<" not found in array"<<endl;
	    }else{
	        cout<<x<<" is found at index "<<i<<endl;
	    }
	}
	return 0;
}