Typorithm · medium

Binary Search

▷ Interactive algorithm labsearchbinary-searchboundarieslogarithmic-time
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn Binary Search

0%

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.

Preparing algorithm lab…
01

Use left and right boundaries.

02

Check while left <= right.

03

Use Math.floor for the middle index.

04

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;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Function declaration

Binary Search expects a sorted array and a target value.

function binarySearch(arr, target)

2. Left boundary

left starts at the first searchable index.

let left = 0

3. Right boundary

right starts at the last valid index.

let right = arr.length - 1

4. Inclusive range

Use <= so a one-item search range is still checked.

while (left <= right)

5. Middle index

Math.floor turns the midpoint calculation into a valid integer index.

Math.floor((left + right) / 2)

6. Return index

When the middle value matches target, return the middle index.

if (arr[mid] === target) return mid

7. Discard left half

If middle is too small, discard it and everything to its left.

left = mid + 1

8. Discard right half

If middle is too large, discard it and everything to its right.

right = mid - 1

9. Not found

Return -1 after the search range becomes empty.

return -1

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

Binary Search: Visual Walkthrough & Practice · Typorithm | ApplyDjinn