Parcel Search

Write a binary search in JavaScript. Watch it find a parcel on a sorted shelf, then see what happens when the parcel is missing.

Write the search

The parcel IDs are distinct and sorted from smallest to largest. Return the target’s zero-based index, or −1 if it’s missing. For example, finding 25 in [12, 25, 41] returns 1. Compare the middle ID using ids[mid].

Need a hint?

With inclusive bounds, keep searching while low <= high. Start each pass at Math.floor((low + high) / 2).

How do I shrink the range?

If the middle ID is too small, every position through the middle can be discarded. Move the lower bound one past the middle. For a middle ID that is too large, move the upper bound one before it.

Step through the debugging lab →

Test shelves

Parcel shelf

Target ID 67
  1. Index 0ID 12
  2. Index 1ID 18
  3. Index 2ID 25
  4. Index 3ID 31
  5. Index 4ID 46
  6. Index 5ID 52
  7. Index 6ID 67