Write a function to perform a binary search on a sorted array of integers to find the index of a given target value. If the target is not found in the array, return -1.
- The function should take two inputs: a sorted array of integers and a target integer.
- The function must use the binary search algorithm to find the target.
- Do not use library functions or methods for the binary search; implement the algorithm manually.
Input: array = [-5, 1, 3, 7, 9, 12, 14]
, target = 9
Output: 4
(because array[4] = 9)
Input: array = [-15, -10, -3, 0, 5, 8, 12]
, target = 6
Output: -1
(because 6 is not in the array)
Binary search involves repeatedly dividing the search interval in half. Begin with the entire array. If the value of the target is less than the value in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Continue checking until the value is found or the interval is empty.
function binarySearch(array, target) {
// Implement the binary search algorithm
return -1;
}
// Test cases
console.log(binarySearch([-5, 1, 3, 7, 9, 12, 14], 9)); // Should return 4
console.log(binarySearch([-15, -10, -3, 0, 5, 8, 12], 6)); // Should return -1
package main
import (
"fmt"
)
func binarySearch(array []int, target int) int {
// Implement this function
return -1
}
func main() {
fmt.Println(binarySearch([]int{-5, 1, 3, 7, 9, 12, 14}, 9)) // Should return 4
fmt.Println(binarySearch([]int{-15, -10, -3, 0, 5, 8, 12}, 6)) // Should return -1
}
def binary_search(array, target):
# Implement the binary search algorithm
pass
# Test cases
print(binary_search([-5, 1, 3, 7, 9, 12, 14], 9)) # Should return 4
print(binary_search([-15, -10, -3, 0, 5, 8, 12], 6)) # Should return -1