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

Commit c7adac0

Browse files
committed
feat: binarySearch
1 parent 0b71aef commit c7adac0

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed

binary-search.js

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
/**
2+
* 二分搜索 从一个数组中搜索一个确定的数
3+
*/
4+
5+
var search = function(nums, target, offset = 0) {
6+
let medium = Math.floor(nums.length / 2)
7+
let mediumVal = nums[medium]
8+
let left = nums.slice(0, medium)
9+
let right = nums.slice(medium, nums.length)
10+
11+
if (nums.length === 1 && mediumVal !== target) {
12+
return -1
13+
}
14+
15+
if (mediumVal > target) {
16+
return search(left, target, offset)
17+
} else if (mediumVal < target) {
18+
return search(right, target, offset + left.length)
19+
} else if (mediumVal === target) {
20+
return medium + offset
21+
}
22+
}
23+
console.log(search([1, 2, 3, 4, 5], 2))

0 commit comments

Comments
 (0)