Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 4df3be6

Browse files
committed
feat: 二分查找-bobo
1 parent 27e157e commit 4df3be6

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

.prettierrc

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
11
{
2-
"printWidth": 140
2+
"printWidth": 140,
3+
"tabWidth": 2
34
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
function binarySearch(arr, n, target) {
2+
// 在[l...r]的范围里寻找target
3+
let l = 0;
4+
let r = n - 1;
5+
while (l <= r) {
6+
let mid = Math.round((l + r) / 2);
7+
8+
if (arr[mid] === target) {
9+
return mid;
10+
}
11+
12+
if (target > arr[mid]) {
13+
l = mid + 1; // 在[mid+1...r]的范围里寻找target
14+
} else {
15+
r = mid - 1;
16+
}
17+
}
18+
return -1;
19+
}
20+
21+
console.log(console.log(binarySearch([1, 2, 3, 4, 5], 5, 2)));

0 commit comments

Comments
 (0)