Bytes
rocket

Your Success, Our Mission!

6000+ Careers Transformed.

Visualizing the Algorithm (A Dry Run)

Last Updated: 25th February, 2026

Reading about a sorting algorithm is one thing, but seeing it in action is where the logic truly clicks. A dry run is a manual walkthrough of the algorithm, step by step, which helps in creating a strong mental model. Let's perform a Bubble Sort visualization with a simple unsorted array to see exactly how the elements bubble their way to their correct positions.

Let's take the following unsorted array: 

1->2->4->5->8

Pass 1: Bubbling the Largest Element

In the first pass, our goal is to move the largest number to the very end of the array.

ComparisonArray State BeforeActionJustificationArray State After
(5, 1)[5, 1, 4, 2, 8]Swap5 > 1, so they are in the wrong order[1, 5, 4, 2, 8]
(5, 4)[1, 5, 4, 2, 8]Swap5 > 4, so they are in the wrong order[1, 4, 5, 2, 8]
(5, 2)[1, 4, 5, 2, 8]Swap5 > 2, so they are in the wrong order[1, 4, 2, 5, 8]
(5, 8)[1, 4, 2, 5, 8]No Swap5 < 8, so they are in the correct order[1, 4, 2, 5, 8]

Result after Pass 1: [1, 4, 2, 5, 8] Notice that the largest element, 8, has successfully bubbled up to its final, sorted position. We no longer need to include it in our comparisons.

Pass 2: Bubbling the Second-Largest Element

Now, we repeat the process, but we only need to iterate up to the fourth element (index 3), since the last one is already sorted.

ComparisonArray State BeforeActionJustificationArray State After
(1, 4)[1, 4, 2, 5, 8]No Swap1 < 4, correct order[1, 4, 2, 5, 8]
(4, 2)[1, 4, 2, 5, 8]Swap4 > 2, wrong order[1, 2, 4, 5, 8]
(4, 5)[1, 2, 4, 5, 8]No Swap4 < 5, correct order[1, 2, 4, 5, 8]

Result after Pass 2: [1, 2, 4, 5, 8] The second-largest element, 5, is now in its correct place. This step-by-step sorting example clearly shows how the sorted portion of the array grows from the right.

Pass 3: The "Aha!" Moment

Let's proceed with the third pass, now only considering the first three elements.

ComparisonArray State BeforeActionJustificationArray State After
(1, 2)[1, 2, 4, 5, 8]No Swap1 < 2, correct order[1, 2, 4, 5, 8]
(2, 4)[1, 2, 4, 5, 8]No Swap2 < 4, correct order[1, 2, 4, 5, 8]

Result after Pass 3:

Here's the crucial part: in this pass, no swaps were made. The optimized version of the Bubble Sort in Java would recognize this. It's a signal that the array is now fully sorted, and the algorithm can terminate early without completing unnecessary passes.

This algorithm dry run makes it clear how the Bubble Sort method, despite its simplicity, methodically arranges data. By visualizing the swaps in each pass, you can build a solid understanding of this foundational Java sorting algorithm.

Module 1: How Bubble Sort WorksVisualizing the Algorithm (A Dry Run)

Top Tutorials

Related Articles