Lesson 4 of 8

Binary search

Goal

From a thousand comparisons down to ten

01

Explanation

Linear search goes through the items one by one, so a million items can take a million comparisons. If the array is sorted, though, twenty comparisons are enough.

The idea is to look at the item in the middle. If it's the one you want, you're done. If it's larger than your target, the target is in the left half; otherwise it's in the right half. Either way, each step rules out half of what's left.

Watch out for two things. First, write the condition as while (lo <= hi) with the equals sign, or you'll miss the last remaining item. Second, compute the middle with Math.floor((lo + hi) / 2).

02

Your task

Write binarySearch(sorted, target) to return the item's position if you find it, or -1 if you don't.

Checks

6 checks
  1. Finds a value in the middle
  2. Finds the first and last items
  3. Returns -1 for a missing value
  4. An empty array returns -1 without freezing the page
  5. Finds items at different positions in a large array
  6. A value smaller or larger than every item returns -1
03

Hints

0/3
Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.

index.html
Preview
index.html100%
–/6

Press “Run and check” to grade your code.

6 checks listed under “Your task”.

Track lessons0 of 8 done

Write functions for searching, sorting, grouping and flattening nested lists once, then reuse them in every project after that.

Advanced level, 8 lessons, 1.5 hours in total.