二分查找的变形问题
let arr = [1, 8, 8, 8, 8, 8, 8, 8, 11, 18]
let index = bsearch(arr, 8)
let indexEnd = bsearchEnd(arr, 8)
let indexGreatOrEqual = bsearchGreatOrEqual(arr, 10)
let indexLessOrEqual = bsearchLessOrEqual(arr, 10)
console.log(index, indexEnd, indexGreatOrEqual, indexLessOrEqual)
function bsearch(arr, value) {
let low = 0
let high = arr.length - 1
while (low <= high) {
let mid = low + ((high - low) >> 1)
if (value > arr[mid]) {
low = mid + 1
} else if (value < arr[mid]) {
high = mid - 1
} else {
if (mid == 0 || arr[mid - 1] < value) {
return mid
} else {
high = mid - 1
}
}
}
return -1
}
function bsearchEnd(arr, value) {
let low = 0
let high = arr.length - 1
while (low <= high) {
let mid = low + ((high - low) >> 1)
if (value > arr[mid]) {
low = mid + 1
} else if (value < arr[mid]) {
high = mid - 1
} else {
if (mid == arr.length - 1 || value < arr[mid + 1]) {
return mid
} else {
low = mid + 1
}
}
}
return -1
}
function bsearchGreatOrEqual(arr, value) {
let low = 0
let high = arr.length - 1
while (low <= high) {
let mid = low + ((high - low) >> 1)
if (value > arr[mid]) {
low = mid + 1
} else {
if (mid == 0 || arr[mid - 1] < value) {
return mid
} else {
high = mid - 1
}
}
}
return -1
}
function bsearchLessOrEqual(arr, value) {
let low = 0
let high = arr.length - 1
while (low <= high) {
let mid = low + ((high - low) >> 1)
if (value < arr[mid]) {
high = mid - 1
} else {
if (mid == arr.length - 1 || arr[mid + 1] > value) {
return mid
} else {
low = mid + 1
}
}
}
return -1
}