forked from wangzheng0822/algo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbinary-find.js
90 lines (82 loc) · 2.43 KB
/
binary-find.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/**
* 二分查找
*
* Author: nameczz
*/
// 查找第一个等于给定值
const biaryFindFirst = (sortedArr, target) => {
if (sortedArr.length === 0) return -1
let low = 0
let high = sortedArr.length - 1
while (low <= high) {
const mid = Math.floor((low + high) / 2)
if (target < sortedArr[mid]) {
high = mid - 1
} else if (target > sortedArr[mid]) {
low = mid + 1
} else {
if (mid === 0 || sortedArr[mid - 1] < target) return mid
high = mid - 1
}
}
return -1
}
// 查找最后一个相等的数
const biaryFindLast = (sortedArr, target) => {
if (sortedArr.length === 0) return -1
let low = 0
let high = sortedArr.length - 1
while (low <= high) {
const mid = Math.floor((low + high) / 2)
if (target < sortedArr[mid]) {
high = mid - 1
} else if (target > sortedArr[mid]) {
low = mid + 1
} else {
if (mid === sortedArr.length - 1 || sortedArr[mid + 1] > target) return mid
low = mid + 1
}
}
return -1
}
// 查找第一个大于等于给定值的元素
const biaryFindFistBig = (sortedArr, target) => {
if (sortedArr.length === 0) return -1
let low = 0
let high = sortedArr.length - 1
while (low <= high) {
const mid = Math.floor((low + high) / 2)
if (target <= sortedArr[mid]) {
if (mid === 0 || sortedArr[mid - 1] < target) return mid
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
// 查找最后一个小于等于给定值的元素
const biaryFindLastSmall = (sortedArr, target) => {
if (sortedArr.length === 0) return -1
let low = 0
let high = sortedArr.length - 1
while (low <= high) {
const mid = Math.floor((low + high) / 2)
if (target < sortedArr[mid]) {
high = mid - 1
} else {
if (mid === sortedArr.length - 1 || sortedArr[mid + 1] >= target) return mid
low = mid + 1
}
}
return -1
}
const arr = [1, 2, 3, 4, 4, 4, 4, 4, 6, 7, 8, 8, 9]
const first = biaryFindFirst(arr, 4)
console.log(`FindFirst: ${first}`)
const last = biaryFindLast(arr, 4)
console.log(`FindLast: ${last}`)
const FisrtBig = biaryFindFistBig(arr, 5)
console.log(`FindFisrtBig: ${FisrtBig}`)
const LastSmall = biaryFindLastSmall(arr, 4)
console.log(`FindLastSmall: ${LastSmall}`)