Bubble Sort Explained: Step-by-Step Trace, Complexity and Exam Traps
Trace bubble sort comparison by comparison, prove why it works, and learn how loop variants change operation counts, stability and best-case time.
KnowledgeGate Team
Exam prep & CS education

Bubble sort sounds obvious until a question asks for the array after a particular pass, the exact number of comparisons or swaps, or whether an implementation is stable and adaptive. The answer can change with one loop bound or one early-exit flag. Tracing every comparison identifies the fixed suffix, the loop invariant proves correctness, and the implementation variant determines the operation counts.
Bubble Sort: The Core Idea and the Exact Algorithm
For ascending order, bubble sort repeatedly scans from left to right and compares adjacent elements. It swaps A[j] and A[j+1] only when A[j] > A[j+1].
The name comes from what each complete pass achieves. The largest value in the active prefix keeps moving right whenever it meets a smaller neighbour. By the end of that pass, it has reached the right end of the prefix.
for i = 0 to n - 2
swapped = false
for j = 0 to n - i - 2
compare A[j] with A[j+1]
if A[j] > A[j+1]
swap A[j] and A[j+1]
swapped = true
if swapped == false
stopThe shrinking upper bound avoids rechecking the sorted suffix. A comparison inspects one adjacent pair, a swap exchanges an inverted pair, and a pass is one traversal of the current unsorted prefix.
This implementation is in-place, stable because it uses strict >, and adaptive because the early-exit flag detects an already sorted array. Without that flag, bubble sort is not adaptive.
Worked Example: Sort [5, 1, 4, 2, 8] Step by Step
Start with [5,1,4,2,8] and sort in ascending order.
Pass 1, four comparisons:
Compare 5 and 1. Swap:
[1,5,4,2,8].Compare 5 and 4. Swap:
[1,4,5,2,8].Compare 5 and 2. Swap:
[1,4,2,5,8].Compare 5 and 8. No swap:
[1,4,2,5,8].
Pass 1 uses 4 comparisons and 3 swaps. The fixed suffix is now [8].
Pass 2, three comparisons:
Compare 1 and 4. No swap:
[1,4,2,5,8].Compare 4 and 2. Swap:
[1,2,4,5,8].Compare 4 and 5. No swap:
[1,2,4,5,8].
Pass 2 uses 3 comparisons and 1 swap. The fixed suffix is [5,8].
Pass 3, two comparisons: compare 1 with 2, then 2 with 4. Neither pair needs a swap, so swapped remains false and the optimized algorithm stops at [1,2,4,5,8].
The optimized run therefore executes 3 passes, 9 comparisons and 4 swaps. An unoptimized loop would also execute Pass 4, compare 1 with 2 once, and finish with 10 comparisons. Neither 9 nor 10 is a universal answer. Always name the implementation.

Why Bubble Sort Is Correct
The useful loop invariant is: after k full passes, the k largest elements occupy the final k positions in sorted order. In the example, Pass 1 fixes 8, and Pass 2 fixes 5 immediately before 8.
Before any pass, the sorted suffix is empty, so the claim is true initially. During a pass, the larger member of each inverted adjacent pair moves right. The largest value in the active prefix therefore reaches the prefix's final position. This extends the sorted suffix by one and maintains the invariant.
After at most n - 1 passes, no unsorted prefix remains. With early exit, a pass containing no swap proves that no adjacent inversion remains. If no adjacent pair is inverted, the entire array is sorted.
Bubble sort is also stable when the comparison is strict. Trace tagged equal keys [2_A,2_B,1]. The first comparison does not swap 2_A and 2_B; the next swap gives [2_A,1,2_B]; the second pass gives [1,2_A,2_B]. Their original order is preserved. Changing the condition to >= may swap equal keys and destroy stability.
Time, Space and Operation Counts
The unoptimized comparison count is
(n - 1) + (n - 2) + ... + 1 = n(n - 1)/2.
For n = 5, that is 4 + 3 + 2 + 1 = 10. Reverse input [5,4,3,2,1] makes all 10 comparisons produce swaps, so worst-case time is Theta(n^2). Average time is also Theta(n^2).
Sorted input separates the variants clearly. On [1,2,3,4,5], the flag-based version performs one pass, 4 comparisons and 0 swaps, giving a Theta(n) best case. The unoptimized version still performs 10 comparisons, so its best case remains Theta(n^2). Both use O(1) auxiliary space. Time Complexity: Big-O, Theta, Omega & Master Theorem explains why an exact count and an asymptotic class answer different questions.
Bubble sort is reasonable for tiny or nearly sorted inputs, for teaching loop invariants, and where simplicity matters more than scale. It is generally a poor default for large unsorted inputs. Its adjacent swaps, early-exit check and growing sorted suffix determine a bubble-sort trace. For cross-family choice by stability, space and growth rate, use Sorting Algorithms: Complexity, Stability, n log n Bound.

Common Bubble Sort Traps and Faulty Traces
One pass does not sort the array. On [3,2,1], Pass 1 produces [2,1,3]. Only 3 is guaranteed to be final. Pass 2 is still required to reach [1,2,3].
The inner-loop bound is easy to miswrite. On outer pass i, the final valid left index is n - i - 2, because the code also reads A[j+1]. Using j <= n - i - 1 reads beyond the active range. A fixed safe upper bound can avoid an invalid access, but it accepts redundant work.
Three more implementation traps deserve a quick check:
Resetting
swappedinside the inner loop can cause a false early exit.Swapping on
>=can break stability.Reversing the comparison to
<sorts in descending order and moves the smallest active value right. Name the direction before stating what a pass fixes.
How Exams Test Bubble Sort
Most bubble sort questions fit four buckets: trace the array after k passes, count comparisons or swaps, identify best, average or worst complexity, or classify the algorithm as stable, in-place and adaptive. Before calculating, check whether there is an early-exit flag and whether a pass means one complete traversal of the current inner loop.
After two complete unoptimized ascending passes on
[7,3,5,1,4], what is the array, and how many comparisons and swaps have occurred?
Pass 1 is [7,3,5,1,4] to [3,7,5,1,4] to [3,5,7,1,4] to [3,5,1,7,4] to [3,5,1,4,7]. That is 4 comparisons and 4 swaps.
Pass 2 compares 3 with 5 without swapping, swaps 5 with 1 to get [3,1,5,4,7], then swaps 5 with 4 to get [3,1,4,5,7]. Across both passes, the correct total is 7 comparisons and 6 swaps.
KnowledgeGate has over 10 live practice questions on Bubble Sort. Use them to practise identifying the exact loop variant before counting.
Bubble Sort in the Shortest Useful Form
Bubble sort follows these rules:
Compare adjacent elements.
Swap only inverted pairs.
One pass fixes the largest active value at the right.
Shrink the active prefix.
Stop early after a no-swap pass.
With strict >, bubble sort is stable. It is in-place with O(1) extra space, has a Theta(n) optimized best case, and takes Theta(n^2) time on average and in the worst case.
Finish with [4,1,3,2]. Pass 1 ends [1,3,2,4] after 3 comparisons and 3 swaps. Pass 2 ends [1,2,3,4] after 2 more comparisons and 1 more swap. Pass 3 makes 1 comparison and no swap. The optimized totals are 6 comparisons and 4 swaps. Reproduce them on paper rather than merely reading them.
For the full DSA sequence, continue with GATE Guidance by Sanchit Sir. Use the GATE Test Series for timed application, or browse the wider preparation path through the GATE category.
Keep learning
Merge Sort Explained: Step-by-Step Trace, Complexity and Exam Questions
Follow Merge Sort from its inclusive-index pseudocode through a complete seven-element trace. Then revise its recurrence, stability, auxiliary space and common exam question forms.
Selection Sort Explained: Step-by-Step Trace, Complexity and Exam Traps
Learn the invariant behind Selection Sort, trace every pass, derive its exact comparison count, and avoid common stability and swap-count traps.
Bubble Sort MCQs: 12 Solved Questions with Explanations
Practise 12 Bubble Sort questions on time complexity, array tracing, swap counts, the flag optimisation, and a GATE numerical, with each answer explained.
Coding Questions for GATE CS: Trace Outputs and Complexity Step by Step
Learn a reliable way to solve coding output and complexity questions. Three fully traced C examples cover loops, mutation, recursion and operation counts.





