Binary search in Java, step by step

Binary search throws away half of a sorted array on every step. Step through it and watch low, middle and high move until the search finds the target or runs out of room.

Source

line 1
Line that just executed Next line to execute
Sign in to share

Call stack

1
main()
line 1
Step 1/1

What to watch

  • middle is always halfway between low and high, rounded down by integer division.
  • When the middle value is too small, low jumps past it. When it is too big, high drops below it.
  • The loop ends after only a few steps, even though the array has seven values.

Try changing it

  • Search for a value that is not in the array and see how the method returns -1.
  • Double the array length and count how many more steps it takes.

Edit the code above and press Visualize to see your version run.

More Java examples

Or open the Java visualizer and paste your own code.