We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent 55723b7 commit 90eb745Copy full SHA for 90eb745
Template/Maths/Binary-Search/Binary-Search.cpp
@@ -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