logo
SEE ALGORITHMS
SORTING
    Bubble Sort
    Insertion Sort
    Selection Sort
    Heap Sort
    Radix Sort
    Merge Sort
    Quick Sort

Bubble Sort

Bubble Sort is a simple sorting algorithm that works by repeatedly swapping adjacent elements if they are in the wrong order. This process continues until the list is fully sorted. While it's easy to understand, Bubble Sort is not very efficient for large datasets due to its quadratic time complexity. It’s often used for educational purposes or as a baseline for comparison with other sorting algorithms.


Pseudocode

for i = 1 to (n - 1):
    swapped = false
    for j = 1 to (n - i):
        if arr[j] < arr[j - 1]:
            swap(j, j - 1)
            swapped = true
    if not swapped: break

Visualizer

Select number of elements:  


How It Works

Bubble Sort begins at the start of the array and compares the first two elements. If the first element is greater than the second, they are swapped. The algorithm then moves to the next pair and repeats the comparison. After one complete pass through the array, the largest element will have "bubbled up" to the last position. The algorithm then repeats the process for the remaining unsorted portion, ignoring the already-sorted elements at the end. This continues until no swaps are needed in a full pass, indicating the array is sorted.

When To Use

Bubble Sort is primarily used as a teaching tool to introduce sorting concepts because of its simplicity. In practice, more efficient divide-and-conquer algorithms are preferred for large datasets. However, Bubble Sort can be useful for very small arrays or when the data is nearly sorted, as its optimized version achieves O(n) performance in the best case.

Time & Space Complexity

Metric / Operation
Complexity
Description
Best CaseO(n)When the array is already sorted and the optimized version detects no swaps in the first pass.
Average CaseO(n²)On average, each element must be compared with every other element.
Worst CaseO(n²)When the array is sorted in reverse order, every possible swap must be performed.
Space ComplexityO(1)Bubble Sort is an in-place algorithm that only requires a constant amount of additional memory for the swap variable.

Curious to Learn More?

Hand-picked resources to deepen your understanding

Beginner Friendly
Coding Interview Bootcamp: Algorithms + Data Structures

Learn essential data structures and algorithms step-by-step with practical JavaScript examples.

Practical Guide
JavaScript Algorithms & Data Structures Masterclass

Master DSA fundamentals, problem-solving techniques, and advanced structures using JavaScript.

Deep Dive
Master the Coding Interview: Data Structures + Algorithms

Prepare for top tech interviews with advanced DSA concepts and real-world coding challenges.

Learn DSA on Udemy
Learn DSA on Udemy
As an Udemy Associate, I earn from qualifying purchases.

© 2025 See Algorithms. Code licensed under MIT, content under CC BY-NC 4.0.