Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

binary search c++

#include <vector>
using namespace std;

int binarySearch(vector<int> v, int x) {
	int l = 0, r = v.size() - 1, mid;

	while (l <= r) { 
		mid = l + (r - l) / 2;
		if (v[mid] == x) return mid;
		else if (v[mid] > x) {
			r = mid - 1;
		}
		else if(v[mid] < x) {
			l = mid + 1;
		}
	}
	return -1;
} 
 
PREVIOUS NEXT
Tagged: #binary #search
ADD COMMENT
Topic
Name
6+7 =