实现如下:
let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8]
function findIndex(arr, num) {
let len = arr.length
let st = 0
let end = len - 1
while ( st <= end ) {
let mid = Math.floor((st+end)/2)
if ( num == arr[mid] ) {
return mid
} else if ( num > arr[mid] ) {
st = mid + 1
} else {
end = mid -1
}
}
return -1
}
findIndex(arr, 5)
网友评论