Back to Home

Bubble Sort

A simple sorting algorithm that repeatedly steps through the list, compares adjacent elements and swaps them if they are in the wrong order.

Visualization

Step 1 / 16
Speed:

Details

Analogy

Imagine people lining up for a photo, ordered by height. You compare each pair of adjacent people and swap them if the taller person is on the left. You repeat this pass until no more swaps are needed, and the line is perfectly ordered from shortest to tallest.

Purpose

To sort an array of elements by repeatedly swapping adjacent elements that are out of order. The pass through the list is repeated until the list is sorted.

Use Cases

Primarily used for educational purposes due to its simplicity. It is not suitable for large datasets as its average and worst-case time complexity are quite high.

Algorithm Steps

Line 1
1
function bubbleSort(array):
2
n = length(array)
3
for i = 0 to n - 1:
4
swapped = false
5
for j = 0 to n - i - 2:
6
if array[j] > array[j + 1]:
7
swap(array[j], array[j + 1])
8
swapped = true
9
if not swapped:
10
break
11
return array
Current
Executed
Pending

Explanation

What's Happening?

Step 1/16

Start of Pass 1. Compare the first two elements: 5 and 3.

Updates with each step • Clickfor full view

Code Implementation

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
    return arr
Bubble Sort - Interactive Visualization | AlgoViz | AlgoViz