Your Success, Our Mission!
6000+ Careers Transformed.
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
In the first pass, our goal is to move the largest number to the very end of the array.
| Comparison | Array State Before | Action | Justification | Array State After |
|---|---|---|---|---|
| (5, 1) | [5, 1, 4, 2, 8] | Swap | 5 > 1, so they are in the wrong order | [1, 5, 4, 2, 8] |
| (5, 4) | [1, 5, 4, 2, 8] | Swap | 5 > 4, so they are in the wrong order | [1, 4, 5, 2, 8] |
| (5, 2) | [1, 4, 5, 2, 8] | Swap | 5 > 2, so they are in the wrong order | [1, 4, 2, 5, 8] |
| (5, 8) | [1, 4, 2, 5, 8] | No Swap | 5 < 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.
| Comparison | Array State Before | Action | Justification | Array State After |
|---|---|---|---|---|
| (1, 4) | [1, 4, 2, 5, 8] | No Swap | 1 < 4, correct order | [1, 4, 2, 5, 8] |
| (4, 2) | [1, 4, 2, 5, 8] | Swap | 4 > 2, wrong order | [1, 2, 4, 5, 8] |
| (4, 5) | [1, 2, 4, 5, 8] | No Swap | 4 < 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.
| Comparison | Array State Before | Action | Justification | Array State After |
|---|---|---|---|---|
| (1, 2) | [1, 2, 4, 5, 8] | No Swap | 1 < 2, correct order | [1, 2, 4, 5, 8] |
| (2, 4) | [1, 2, 4, 5, 8] | No Swap | 2 < 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.
Top Tutorials
Related Articles