1. Function declaration
Binary Search expects a sorted array and a target value.
function binarySearch(arr, target)Typorithm · medium
Step 1 of 8 · intro card
Search Algorithms
Binary Search repeatedly discards half of a sorted search range.
Binary Search only works when the array is sorted.
It checks the middle value, then decides which half can be ignored.
The left and right boundaries move inward until the target is found or the range is empty.
Use left and right boundaries.
Check while left <= right.
Use Math.floor for the middle index.
Move with mid + 1 and mid - 1.
function binarySearch(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;
if (arr[mid] < target) left = mid + 1;
else right = mid - 1;
}
return -1;
}Connect each part of the code to the concept before you type.
Binary Search expects a sorted array and a target value.
function binarySearch(arr, target)left starts at the first searchable index.
let left = 0right starts at the last valid index.
let right = arr.length - 1Use <= so a one-item search range is still checked.
while (left <= right)Math.floor turns the midpoint calculation into a valid integer index.
Math.floor((left + right) / 2)When the middle value matches target, return the middle index.
if (arr[mid] === target) return midIf middle is too small, discard it and everything to its left.
left = mid + 1If middle is too large, discard it and everything to its right.
right = mid - 1Return -1 after the search range becomes empty.
return -1Read the concept map and follow the code breakdown.
Type the implementation, repair mistakes and work through every recall exercise.
Use the final check without hints; revisit weak concepts in short practice sessions.
Algorithm lab · interactive
InputArray [1,3,5,7,9,11,13,15] · target 9
Follow temporary values, local state and supporting structures at this step.
Local state · indices and saved values
Around this step
Small, reproducible examples · ← → step · Space play/pause · Home/End first/last state