Algorithm

Bubble Sort

sorting

Bubble Sort is one of the simplest sorting algorithms that repeatedly steps through the list, compares adjacent elements, and swaps them if they are in the wrong order. The algorithm gets its name because smaller elements "bubble" to the top of the list with each iteration. While conceptually simple, Bubble Sort is primarily used for educational purposes due to its inefficiency with large datasets. Its average and worst-case time complexity is O(n²), making it impractical for real-world applications with significant data. However, it has the advantage of being able to detect if the list is already sorted (best-case O(n) with optimization) and requires minimal extra memory space.

Time: Best: O(n), Average/Worst: O(n²)
Space: O(1)

Visualization

Press Play or step forward to watch the algorithm run.

Controls & Input

1x
Array size: 7 elements

Implementation

Pseudocode

0 function bubbleSort(array):
1 n = length(array)
2
3 // Outer loop: iterate through the entire array
4 for i = 0 to n-2:
5 swapped = false
6
7 // Inner loop: compare adjacent elements
8 for j = 0 to n-i-2:
9 // If elements are in wrong order, swap them
10 if array[j] > array[j+1] then
11 swap array[j] and array[j+1]
12 swapped = true
13
14 // If no elements were swapped in this pass,
15 // the array is already sorted
16 if not swapped then
17 break