Find it please

QUESTION

Given a sorted array arr[] of n elements, write a program using binary search to search a given element x in arr[]. \nInput:\nNumber of elements, elements in sorted order and finally the element to be searched in the array.\n\nOutput:\nThe location where the element is found\n\nSample Input 1:\n5\n2 4 10 4 2\n4\nOutput:\n4 found at location 2.

“TESTCASE_1”: “5\n2 4 10 20 44\n10\n###—###SEPERATOR—###—\n10 found at location 3”, “TESTCASE_2”: “7\n5 10 22 67 78 79 99\n4\n###—###SEPERATOR—###—\n4 not found”, “TESTCASE_3”: “9\n5 9 20 39 44 60 79 88 95\n39\n###—###SEPERATOR—###—\n39 found at location 4”, “TESTCASE_4”: “5\n2 4 10 4 2\n4\n###—###SEPERATOR—###—\n4 found at location 2”, “TESTCASE_5”: “0\n###—###SEPERATOR—###—\n0

ANSWER

#include <iostream>
using namespace std;
void bsearch(int a[],int f,int l, int x){
	
}

int main()
{	int n,i;
 	cin>>n;
 	int a[n];
 	for(i=0;i<n;i++){
    	cin>>a[i];
    }
 	int x;
 	cin>>x;
 	int f=0,l=n-1;
 	int m=(f+l)/2;
 	while(f<=l){
    	if(a[m]<x){
        	f=m+1;
        }else if(a[m]==x){
        	cout<<x<<" found at location "<<m+1;
          	break;
        }else{
        	l=m-1;
        }
      m=(f+l)/2;
    }
 
	if(f>l){
    	cout<<x<<" not found";
    }

	return 0;
}
Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Powered By
CHP Adblock Detector Plugin | Codehelppro