Sorted
Swapping
Comparing

Algorithm Details

Bubble Sort Explanation

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

How it works

  1. Compare adjacent elements in the array
  2. Swap them if they are in the wrong order
  3. Continue through the array until no more swaps are needed
  4. The largest elements 'bubble' to the end with each pass

Complexity Analysis

Time Complexity

O(n²)

Space Complexity

O(1)

Stable

Yes

In-place

Yes

Best Use Cases

  • Educational purposes and understanding basic sorting concepts
  • Small data sets where simplicity is more important than efficiency
  • When the list is already almost sorted (adaptive implementation)

Bubble Sort Implementation

1function bubbleSort(arr) {
2  const n = arr.length;
3  let swapped;
4  
5  for (let i = 0; i < n; i++) {
6    swapped = false;
7    
8    // Last i elements are already in place
9    for (let j = 0; j < n - i - 1; j++) {
10      // Compare adjacent elements
11      if (arr[j] > arr[j + 1]) {
12        // Swap them if they are in the wrong order
13        [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
14        swapped = true;
15      }
16    }
17    
18    // If no swapping occurred in this pass, array is sorted
19    if (!swapped) break;
20  }
21  
22  return arr;
23}
24
25// Example usage:
26const array = [64, 34, 25, 12, 22, 11, 90];
27console.log(bubbleSort([...array]));  // [11, 12, 22, 25, 34, 64, 90]