Skip to content

Commit 90eb745

Browse files
committed
Add binary search template
1 parent 55723b7 commit 90eb745

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// An example of binary search.
2+
// Return the index if the target value could be found in the array, otherwise, return -1;
3+
4+
int binary_search(vector<int> arr, int target) {
5+
int left = 0, right = arr.size() - 1;
6+
while(left <= right) {
7+
int mid = (right - left) / 2 + left;
8+
if (arr[mid] == target) {
9+
return mid;
10+
}
11+
else if (arr[mid] > target){
12+
right = mid - 1;
13+
}
14+
else if (arr[mid] < target){
15+
left = mid + 1;
16+
}
17+
}
18+
return -1;
19+
}

0 commit comments

Comments
 (0)