mirror of
https://github.com/yangshun/tech-interview-handbook.git
synced 2025-07-29 13:13:54 +08:00
Return -1 if target is not in array (#9)
* return -1 if target is not in array * return -1 if target is not in array (python) * <= in binary search while loop
This commit is contained in:

committed by
Yangshun Tay

parent
ae70816718
commit
4fa28c04ee
@ -1,7 +1,7 @@
|
||||
function binarySearch(arr, target) {
|
||||
let left = 0;
|
||||
let right = arr.length - 1;
|
||||
while (left < right) {
|
||||
while (left <= right) {
|
||||
let mid = left + Math.floor((right - left) / 2);
|
||||
if (arr[mid] === target) {
|
||||
return mid;
|
||||
@ -12,15 +12,15 @@ function binarySearch(arr, target) {
|
||||
right = mid - 1;
|
||||
}
|
||||
}
|
||||
return left;
|
||||
return -1;
|
||||
}
|
||||
|
||||
console.log(binarySearch([1, 2, 3, 10], 1) === 0)
|
||||
console.log(binarySearch([1, 2, 3, 10], 2) === 1)
|
||||
console.log(binarySearch([1, 2, 3, 10], 3) === 2)
|
||||
console.log(binarySearch([1, 2, 3, 10], 10) === 3)
|
||||
console.log(binarySearch([1, 2, 3, 10], 9) === 3)
|
||||
console.log(binarySearch([1, 2, 3, 10], 4) === 3)
|
||||
console.log(binarySearch([1, 2, 3, 10], 0) === 0)
|
||||
console.log(binarySearch([1, 2, 3, 10], 11) === 3)
|
||||
console.log(binarySearch([5, 7, 8, 10], 3) === 0)
|
||||
console.log(binarySearch([1, 2, 3, 10], 9) === -1)
|
||||
console.log(binarySearch([1, 2, 3, 10], 4) === -1)
|
||||
console.log(binarySearch([1, 2, 3, 10], 0) === -1)
|
||||
console.log(binarySearch([1, 2, 3, 10], 11) === -1)
|
||||
console.log(binarySearch([5, 7, 8, 10], 3) === -1)
|
||||
|
@ -1,7 +1,7 @@
|
||||
def binary_search(arr, target):
|
||||
left = 0;
|
||||
right = len(arr) - 1
|
||||
while left < right:
|
||||
while left <= right:
|
||||
mid = left + (right - left) // 2;
|
||||
if arr[mid] == target:
|
||||
return mid
|
||||
@ -9,14 +9,14 @@ def binary_search(arr, target):
|
||||
left = mid + 1
|
||||
else:
|
||||
right = mid - 1
|
||||
return left
|
||||
return -1
|
||||
|
||||
print(binary_search([1, 2, 3, 10], 1) == 0)
|
||||
print(binary_search([1, 2, 3, 10], 2) == 1)
|
||||
print(binary_search([1, 2, 3, 10], 3) == 2)
|
||||
print(binary_search([1, 2, 3, 10], 10) == 3)
|
||||
print(binary_search([1, 2, 3, 10], 9) == 3)
|
||||
print(binary_search([1, 2, 3, 10], 4) == 3)
|
||||
print(binary_search([1, 2, 3, 10], 0) == 0)
|
||||
print(binary_search([1, 2, 3, 10], 11) == 3)
|
||||
print(binary_search([5, 7, 8, 10], 3) == 0)
|
||||
print(binary_search([1, 2, 3, 10], 9) == -1)
|
||||
print(binary_search([1, 2, 3, 10], 4) == -1)
|
||||
print(binary_search([1, 2, 3, 10], 0) == -1)
|
||||
print(binary_search([1, 2, 3, 10], 11) == -1)
|
||||
print(binary_search([5, 7, 8, 10], 3) == -1)
|
||||
|
Reference in New Issue
Block a user