Skip to content

Commit 5a27205

Browse files
committed
feat: add binary search
1 parent 5e6ace2 commit 5a27205

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

js/binary_search.js

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022-05-12 22:44:07
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022-05-12 22:44:53
6+
*/
7+
8+
/**
9+
*
10+
* 704. 二分查找
11+
*
12+
* 给定一个 n 个元素有序的(升序)整型数组 nums 和一个目标值 target ,写一个函数搜索 nums 中的 target,如果目标值存在返回下标,否则返回 -1。
13+
*
14+
* 示例 1:
15+
* 输入: nums = [-1,0,3,5,9,12], target = 9
16+
* 输出: 4
17+
* 解释: 9 出现在 nums 中并且下标为 4
18+
*
19+
* 示例 2:
20+
* 输入: nums = [-1,0,3,5,9,12], target = 2
21+
* 输出: -1
22+
* 解释: 2 不存在 nums 中因此返回 -1
23+
*
24+
* 提示:
25+
* 你可以假设 nums 中的所有元素是不重复的。
26+
* n 将在 [1, 10000]之间。
27+
* nums 的每个元素都将在 [-9999, 9999]之间。
28+
*
29+
*/
30+
const search = (nums, target) => {
31+
let i = 0;
32+
let j = nums.length - 1;
33+
let midIndex = 0;
34+
35+
while (i <= j) {
36+
midIndex = Math.floor((i + j) / 2);
37+
const midValue = nums[midIndex];
38+
39+
if (midValue === target) {
40+
return midIndex;
41+
} else if (midValue < target) {
42+
i = midIndex + 1;
43+
} else {
44+
j = midIndex - 1;
45+
}
46+
}
47+
48+
return -1;
49+
};
50+
51+
console.log(search([-1, 0, 3, 5, 9, 12], 9));

0 commit comments

Comments
 (0)