Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

c++ binary search

#include<bits/stdc++.h>
using namespace std;
int main(){
	
	//lets do it
	
    int n;
    cin>>n;
    int arr[n];
    for(int i=0;i<n;i++) cin>>arr[i];
    int target;
    cin>>target; // target=?
    int l=0,h=n-1;
    int index=-1;
    while(l<=h)
    {
    	int mid=(l+h)/2;
    	if(arr[mid]==target){
    		index=mid;
    		break;
		}else if(arr[mid]<target) l=mid+1;
		else h=mid-1;
		
	}
	cout<<"NUMBER FOUND AT INDEX-"<<index<<endl;
	return 0;
}
Source by www.knowprogram.com #
 
PREVIOUS NEXT
Tagged: #binary #search
ADD COMMENT
Topic
Name
6+3 =