Bubble Sort Visualizer
Interactive visualization of bubble sort algorithm with step-by-step code execution
Array Visualization
Controls
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}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
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
Compare Adjacent
Compare each pair of adjacent elements
Swap if Needed
Swap if they are in wrong order
Bubble Up
Largest element moves to correct position
Repeat Passes
Continue until no swaps are needed
Early Termination
Stop if no swaps occur in a pass