Binary search 有好幾種情況,以下根據不同的情況提供相應的解法。
當然這裡有個前提,就是陣列中的元素是已經排序好的。
Binary search 有好幾中情況:
扣除第一種,其他八種情況代表是三個條件的組合:
只要找到目標值,就返回它的索引。沒有找到,就返回 -1。在這個情況中,元素不會重複出現。
function binarySearch(arr, target) {
let left = 0;
let right = arr.length - 1;
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
function binarySearch(arr, target) {
let left = 0
let right = arr.length - 1
let result = -1
while (left <= right) {
let mid = Math.floor((left + right) / 2)
if (arr[mid] <= target) {
result = mid
left = mid + 1
} else {
right = mid - 1
}
}
return result
}
function binarySearch(arr, target) {
let left = 0
let right = arr.length - 1
let result = -1
while (left <= right) {
let mid = Math.floor((left + right) / 2)
if (arr[mid] >= target) {
result = mid
right = mid - 1
} else {
left = mid + 1
}
}
return result
}
function binarySearch(arr, target) {
let left = 0
let right = arr.length - 1
let result = -1
while (left <= right) {
let mid = Math.floor((left + right) / 2)
if (arr[mid] > target) {
result = mid
right = mid - 1
} else {
left = mid + 1
}
}
return result
}
function binarySearch(arr, target) {
let left = 0
let right = arr.length - 1
let result = -1
while (left <= right) {
let mid = Math.floor((left + right) / 2)
if (arr[mid] < target) {
result = mid
left = mid + 1
} else {
right = mid - 1
}
}
return result
}
function binarySearch(arr, target) {
let left = 0
let right = arr.length - 1
let result = -1
while (left <= right) {
let mid = Math.floor((left + right) / 2)
if (arr[mid] === target) {
result = mid
right = mid - 1
} else if (arr[mid] < target) {
left = mid + 1
} else {
right = mid - 1
}
}
return result
}
function binarySearch(arr, target) {
let left = 0
let right = arr.length - 1
let result = -1
while (left <= right) {
let mid = Math.floor((left + right) / 2)
if (arr[mid] === target) {
result = mid
left = mid + 1
} else if (arr[mid] < target) {
left = mid + 1
} else {
right = mid - 1
}
}
return result
}