← Back to DSA Animator
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).