Scriptdrill

Level 2: Arrays and objects Exercise 28 of 76 Free

Binary search

A JavaScript exercise from Scriptdrill. Solve it with a code editor in your browser that runs your function against example and hidden tests, and it is checked the moment you submit.

The task

`sorted` is an array of numbers in ascending order with no duplicates. Return the index of `target`, or `-1` when it is not there. Use binary search: keep a low and a high index and halve the range on every step. One hidden test counts how many elements you read from an array of one million numbers and allows at most 40 reads, so scanning from the start (or `indexOf`) fails it.

What this exercise teaches

Each step discards half of the remaining range, so a million elements take at most 20 reads. The loop condition must be lo <= hi: with lo < hi a range of one element is never checked, which breaks single-element arrays and the last element.

A hint if you get stuck

Start with `lo = 0` and `hi = sorted.length - 1`. While `lo <= hi`, take `mid = Math.floor((lo + hi) / 2)`, return it if it holds the target, otherwise move `lo` to `mid + 1` or `hi` to `mid - 1`.

Try it now, free, no account needed

Every exercise on Scriptdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Arrays and objects