function binarySearchIterative(arr, target) {
let left = 0
let right = arr.length - 1
while (left <= right) {
const 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 binarySearchRecursive(arr, target, left, right) {
if (left > right) {
return -1
}
const mid = Math.floor((left + right) / 2)
if (arr[mid] === target) {
return mid
} else if (arr[mid] < target) {
return binarySearchRecursive(arr, target, mid + 1, right)
} else {
return binarySearchRecursive(arr, target, left, mid - 1)
}
}
const sortedArray = [1, 3, 5, 7, 9, 11, 13]
const target = 7
console.log('반복문 결과:', binarySearchIterative(sortedArray, target))
console.log('재귀 결과:', binarySearchRecursive(sortedArray, target, 0, sortedArray.length - 1))