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.
Call stack
1
main()
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
- Java recursion visualizer
- Bubble sort in Java, step by step
- Java ArrayList visualizer
- Java linked list visualizer
- Java objects and references, visualized
- Java 2D array visualizer
Or open the Java visualizer and paste your own code.