Bubble Sort Visualizer

Interactive visualization of bubble sort algorithm with step-by-step code execution

Array Visualization

64
[0]
34
[1]
25
[2]
12
[3]
22
[4]
11
[5]
90
[6]
Pass: 1 | Position: 1
Comparisons: 0 | Swaps: 0

Controls

SlowFast

Bubble Sort Algorithm

1function bubbleSort(array) {
2  const n = array.length;
3  
4  // Outer loop for number of passes
5  for (let i = 0; i < n - 1; i++) {
6    let swapped = false;
7    
8    // Inner loop for comparisons in current pass
9    for (let j = 0; j < n - i - 1; j++) {
10      
11      // Compare adjacent elements
12      if (array[j] > array[j + 1]) {
13        // Swap elements if they are in wrong order
14        [array[j], array[j + 1]] = [array[j + 1], array[j]];
15        swapped = true;
16      }
17    }
18    
19    // If no swapping occurred, array is sorted
20    if (!swapped) break;
21  }
22  
23  return array;
24}
Step 1 of 8

Get the length of the array

About Bubble Sort

Understanding the fundamentals, properties, and complexity analysis of the bubble sort algorithm

What is Bubble Sort?

Bubble Sort is a simple comparison-based sorting algorithm. It works by repeatedly comparing adjacent elements and swapping them if they are in the wrong order. The largest element "bubbles up" to its correct position in each pass, like bubbles rising to the surface.

Advantages

  • Simple implementation and understanding
  • In-place sorting (O(1) space complexity)
  • Stable sorting algorithm

Disadvantages

  • Poor time complexity O(n²)
  • Inefficient for large datasets
  • Many unnecessary comparisons

Properties

Type:Comparison
Stability:Stable
Best Case:O(n)
Average Case:O(n²)
Worst Case:O(n²)
Space:O(1)

When to Use

Educational Purposes

Learn sorting algorithm concepts

Small Datasets

Arrays with very few elements (< 20)

Nearly Sorted Data

Best case O(n) for almost sorted arrays

Memory Constraints

When space complexity is critical

Simple Implementation

When code simplicity is priority

Algorithm Steps

1

Compare Adjacent

Compare each pair of adjacent elements

2

Swap if Needed

Swap if they are in wrong order

3

Bubble Up

Largest element moves to correct position

4

Repeat Passes

Continue until no swaps are needed

5

Early Termination

Stop if no swaps occur in a pass