Skip to content
Algorithms for Beginners

Problems / Binary search

Find the number

easy

New here? How this page works
  1. Read the Problem tab. Read it twice. Look at the examples: what goes in, what should come out.
  2. Open Break it down. Answer the questions in your own words. This is your plan.
  3. Write code on the right. Start small. Stuck on a blank page? Press “Write my plan as comments”.
  4. Press Run examples. See which examples pass. Red ones show what your code gave and what was expected.
  5. Stuck? Use Hints, one at a time. Still stuck after all of them? Read the Walkthrough. That's learning, not cheating.
  6. Press Submit. It runs hidden tests too. Pass them all, and it's solved.

sorted is a list of different whole numbers, from smallest to largest. Return the position of target in it, or -1 if it isn't there.

Checking every item works, but try to use the order: it lets you rule out half the list with every look.

Examples

  1. Example 1

    Input
    sorted = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91], target = 23
    Output
    5

    23 is at position 5.

  2. Example 2

    Input
    sorted = [2, 5, 8, 12, 16], target = 6
    Output
    -1

    6 would sit between 5 and 8, but it isn't in the list.

  3. Example 3

    Input
    sorted = [-5, 0, 7], target = -5
    Output
    0

Rules

  • sorted has between 0 and 1,000,000 different numbers, from smallest to largest.
  • Don't use indexOf or includes: they check items one by one.
Words on this page, in plain English (3)Open if any word is new to you
Array (list)
A list of values kept in order, inside square brackets. Like a row of numbered lockers.
Index (position)
Where an item sits in a list. Counting starts at 0, not 1, so the first item is at position 0.
Sorted
In order, smallest to biggest (or A to Z). Many fast tricks only work on sorted lists.

Every word, explained simply

Your solution

JavaScript · Press Esc then Tab to leave the editor

function findTheNumber(sorted, target) {
  // Return the position of target, or -1.
}

Blank page fear? (uses your answers from Break it down; comments don’t run).

Results

Run the examples to check your code, then Submit to run every test.

Next steps in binary search