DSA — Sorting Algorithms

Bubble Sort

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
Slow Fast
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
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?
4. Bubble sort is stable. What does that mean?
5. Why is bubble sort taught but rarely shipped?
Bubble Mastery0 / 5 solved
#01Sort ColorsGoogle
#02Majority ElementAmazon
#03Sort an ArraySwiggy
#04Valid AnagramZomato
#05Move ZeroesMeta