Skip to content

Commit 0d48fe9

Browse files
committed
add binarySearch
1 parent a2d3c5e commit 0d48fe9

3 files changed

Lines changed: 70 additions & 0 deletions

File tree

‎.gitignore‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2+
3+
# dependencies
4+
/node_modules
5+
/.pnp
6+
.pnp.js
7+
8+
# testing
9+
/coverage
10+
11+
# production
12+
/build
13+
14+
# misc
15+
.DS_Store
16+
.env.local
17+
.env.development.local
18+
.env.test.local
19+
.env.production.local
20+
21+
npm-debug.log*
22+
yarn-debug.log*
23+
yarn-error.log*
24+
25+
/.vscode

‎JavaScript/Typical/Test.js‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
// 测试二分查找法
2+
var bs = require('./binarySearch');
3+
var arr1 = [0, 1, 2, 3, 4, 5, 10, 23, 44, 66, 88, 99];
4+
console.log(bs.binarySearch1(arr1, 10));
5+
console.log(bs.binarySearch2(arr1, 88));

‎JavaScript/Typical/binarySearch.js‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/*
2+
* 二分查找法
3+
* 前提条件:数组有序
4+
*/
5+
module.exports.binarySearch1 = function binarySearch1(arr, target) {
6+
// 在arr[l...r]之中查找target
7+
let l = 0;
8+
let r = arr.length-1;
9+
while(l <= r) {
10+
// int mid = Math.floor((r+l)/2);
11+
// 防止极端情况下数据溢出
12+
var mid = l + Math.floor((r-l)/2);
13+
if(arr[mid] === target) {
14+
return mid;
15+
}
16+
if(arr[mid] > target) {
17+
r = mid-1;
18+
} else {
19+
l = mid+1;
20+
}
21+
}
22+
return -1;
23+
}
24+
25+
// 用递归的方式写二分查找法
26+
module.exports.binarySearch2 = function binarySearch2(arr, target) {
27+
return __binarySearch2(arr, 0, arr.length-1, target);
28+
}
29+
30+
function __binarySearch2(arr, l, r, target) {
31+
if(l > r) return -1;
32+
var mid = l + Math.floor((r - l)/2);
33+
if(arr[mid] === target)
34+
return mid;
35+
else if(arr[mid] < target) {
36+
return __binarySearch2(arr, mid+1, r, target);
37+
} else {
38+
return __binarySearch2(arr, l, mid-1, target);
39+
}
40+
}

0 commit comments

Comments
 (0)