Write a function called binarySearch which accepts a sorted array and a value and returns the index at which the value exists. Otherwise, return -1.
binarySearch([1,2,3,4,5],2) // 1
binarySearch([1,2,3,4,5],3) // 2
binarySearch([1,2,3,4,5],5) // 4
binarySearch([1,2,3,4,5],6) // -1
binarySearch([
5, 6, 10, 13, 14, 18, 30, 34, 35, 37,
40, 44, 64, 79, 84, 86, 95, 96, 98, 99
], 10) // 2
binarySearch([
5, 6, 10, 13, 14, 18, 30, 34, 35, 37,
40, 44, 64, 79, 84, 86, 95, 96, 98, 99
], 95) // 16
binarySearch([
5, 6, 10, 13, 14, 18, 30, 34, 35, 37,
40, 44, 64, 79, 84, 86, 95, 96, 98, 99
], 100) // -1
function binarySearch(arr, val){
let start = 0;
let end = arr.length-1;
let middle = Math.floor((start+end)/2)
while(arr[middle] !== val && start<=end) {
if(val < arr[middle]) end = middle -1;
else start = middle + 1;
middle = Math.floor((start+end)/2)
}
return arr[middle] === val ? middle : -1
}
start
와 end
포인트를 잡는 것arr[middle]!==val
)이 만족되는 한 계속 돌리는 방법으로 while문이 적절함val
값이 arr
안에 없을 경우, start
가 end
를 넘어서까지 while문이 계속 돌 수 있으므로 start <= end
일 때까지 while문이 돌도록 조건 추가하기