DSA AnimatorDSA animations
Bubble Sort LC #912 Easy Comparison Sort
Problem

Given an array of integers nums, sort the array in ascending order using the Bubble Sort algorithm — repeatedly step through the array, compare each pair of adjacent elements, and swap them if they're in the wrong order. Each full pass "bubbles" the largest remaining element to its correct position at the end.

Example 1
Input: nums = [5,2,9,1,5,6]
Output: [1,2,5,5,6,9]
Constraints: 1 ≤ n ≤ 5*10^4  |  -5*10^4 ≤ nums[i] ≤ 5*10^4
Try Examples
Custom:
Approach
Adjacent Swaps, Largest Bubbles to the End
On each pass, walk left to right comparing nums[j] and nums[j+1]. Swap if out of order. After pass i, the i largest elements are guaranteed sorted at the tail. Stop early if a full pass makes zero swaps. O(n²) time, O(1) space.
Array
Comparing Swapping Sorted
Variables
pass i
—
j
—
comparisons
0
swaps
0
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
For each pass i = 0..n-2 (with early-exit tracking)
2
For j = 0..n-2-i, compare nums[j] and nums[j+1]
3
If nums[j] > nums[j+1] → swap them
4
If a pass makes zero swaps, array is sorted — break early
Best
O(n)
Avg/Worst
O(n²)
Space
O(1)
Why It Works

Invariant: after pass i completes, the last i elements are the i largest values, in sorted position. Each inner pass "bubbles" the current largest unsorted element rightward one swap at a time until it reaches its resting place. The early-exit swapped flag turns best-case (already sorted) input into O(n).

How to solve Bubble Sort

LeetCode 912 · Easy · Sorting Algorithms · Pattern: Adjacent Swaps

Why the obvious approach is slow

Bubble sort is the simplest sort to understand. It is too slow for big inputs, but it teaches how swaps move elements.

The key idea

Walk from left to right, comparing each pair of neighbours. If the left one is bigger, swap them. After one pass, the largest value has bubbled to the end, where it stays. Repeat on the shorter unsorted part. If a pass makes no swap at all, the array is already sorted, so stop early.

Remember

Each pass bubbles the largest remaining value to the end. The swapped flag makes the best case linear.

Run the animation above on your own input, or watch the 1:42 video explanation of Bubble Sort with a dry run and Java code.

More Sorting Algorithms problems