Bubble sort in Java, step by step
Bubble sort compares neighbors and swaps them when they are out of order. Step through it and you can watch the largest value move to the end on every pass of the outer loop.
Call stack
1
main()
Step 1/1
What to watch
- The inner loop compares numbers[j] with numbers[j + 1] and swaps them through temp when the left one is bigger.
- After each pass of the outer loop, the largest remaining value has moved to its final spot at the end.
- The inner loop gets shorter each pass because the end of the array is already sorted.
Try changing it
- Start with an array that is already sorted and count the comparisons.
- Add a boolean that stops early when a pass makes no swaps.
Edit the code above and press Visualize to see your version run.
More Java examples
- Java recursion visualizer
- Binary search 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.