Skip to content
dreamcode
dreamcode
Map
Binary search
Lesson 39 of 48
+15 XP on finish
JS ALGORITHMSChapter 8 · JS Algorithms

Binary Search

indexOf and includes are linear searches: they check items one by one, O(n). Binary search needs a sorted array but is O(log n): look at the middle, throw away the half that cannot hold the target, repeat. A million sorted items need about 20 checks instead of a million.

Worked example

How it reads

  • low and high bound the part of the array that could still hold the target
  • Math.floor keeps mid a whole index
  • 200 items take at most 8 steps
Cloud tip: Binary search is not only for arrays: you can binary search any yes-or-no question that flips once, like "is this version broken?".
index.js
JAVASCRIPT
real JavaScript, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Rewrite find as a binary search. It should still print 6 then -1.

Press Run to check your work.