Skip to content

Commit 764f067

Browse files
committed
feat: solve new question
1 parent d8759ae commit 764f067

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed

binary-search/main.js

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} target
4+
* @return {number}
5+
*/
6+
var search = function(nums, target) {
7+
let l = 0;
8+
let r = nums.length - 1;
9+
10+
while (l <= r) {
11+
// important : to get the middle of array
12+
let mid = Math.floor((l + r) / 2);
13+
14+
// if the target found
15+
if (nums[mid] == target) {
16+
return mid;
17+
}
18+
19+
// if the target is less than the current mid value
20+
if (nums[mid] < target) {
21+
l = mid + 1; // the current mid is left
22+
} else {
23+
r = mid - 1; // the current mid is right
24+
}
25+
}
26+
27+
// target not found in array
28+
return -1;
29+
};
30+

0 commit comments

Comments
 (0)