Bubble Sort

Easy
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Bubble Sort

Approach

Iterate through the array repeatedly, comparing adjacent pairs and swapping them if out of order. After each full pass, the largest unsorted element reaches its correct position at the end. Optimize with an early exit flag: if no swaps occur in a pass, the array is already sorted.

Complexity Analysis

Time
O(n²)
Space
O(1)

Pattern

Basic Sort

Why It Works

Each pass guarantees the next largest element reaches its final position. The early exit optimization makes the best case O(n) for nearly sorted arrays, though average and worst cases remain O(n²).

Updated Feb 2026