easy+150 XPPractice
Binary search over a sorted list
Sorted data turns up constantly on the client: a timeline of messages by timestamp, a price ladder, a list of sorted option values in a combobox. Scanning it linearly wastes the fact that it is sorted.
Implement binarySearch(sorted, target). sorted is an array of numbers in ascending order with no duplicate values, and target is a number. Return the index of target in the array, or -1 when the array does not contain it. An empty array always returns -1.
What it has to do
- Return the index of the target when it is present.
- Return
-1when the target is absent. - Return
-1for an empty array. - Halve the search range each step rather than scanning every element.
Your workspace
Try it yourself· Edit the code, then press Run
Loading playground...
Ready to check it?
5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.
AI Crack & Solution Assist
Stuck? Get instant AI hints or break down the optimal solution.
Stuck? The javascript course covers everything this challenge needs.