← All Exercises
Binary Search Algorithm
intermediatejavascript
Background
Binary search is one of the most important algorithms in computer science, underlying database indexes and search operations.
Problem
Write a function that takes a sorted array and a target value, returning the index of the target if found, or -1 if not present.
Input
A sorted array of numbers and a target number to find.
Output
The index of the target in the array, or -1 if not found.
Sample tests
Sample 1
Input: [1, 3, 5, 7, 9], 5
Expected: 2
Your solution
Learning objective
Master the binary search algorithm, including loop invariants and midpoint calculation.