The simplest sorting algorithm. Repeatedly swap adjacent elements if they are in the wrong order until the largest "bubbles" to the end.
— min read
O(n²)Time Avg
O(1)Space
O(n)Best Case
StableSort
SimpleIn-place
01Live Step-by-Step Animation
SlowFast
Set speed and press Start.
How It Works
Code
Quiz
Practice
01
Compare Neighbors
Pick `arr[j]` and `arr[j+1]`. If left > right, swap them.
02
Bubble Up
Repeat for each element. After one full pass, the largest unsorted element is at its correct final position.
def bubble_sort(arr):
n = len(arr)
for i in range(n):
swapped = False
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
swapped = True
if not swapped: break # Early exit
function bubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n; i++) {
let swapped = false;
for (let j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
swapped = true;
}
}
if (!swapped) break; // Early exit
}
}
void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n; i++) {
boolean swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
int t = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = t;
swapped = true;
}
}
if (!swapped) break; // Early exit
}
}
voidbubble_sort(std::vector<int>& arr) {
int n = (int)arr.size();
for (int i = 0; i < n; i++) {
bool swapped = false;
for (int j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
std::swap(arr[j], arr[j + 1]);
swapped = true;
}
}
if (!swapped) break; // early exit
}
}
1. What does one full pass of bubble sort guarantee?
2. Worst-case time complexity of bubble sort?
3. With the early-exit optimisation, what is the best case and when does it happen?