DSA Lesson 22 of 33

Bubble Sort

Learn the simple comparison-based Bubble Sort algorithm.

Course Progress67%

Theory

Bubble Sort repeatedly compares adjacent elements and swaps them when they are in the wrong order. After each pass, the largest unsorted element moves toward the end. Its average and worst-case time complexity is O(n²).

Example

const numbers = [5, 3, 4, 1]; for (let i = 0; i < numbers.length; i++) { for (let j = 0; j < numbers.length - i - 1; j++) { if (numbers[j] > numbers[j + 1]) { const temp = numbers[j]; numbers[j] = numbers[j + 1]; numbers[j + 1] = temp; } } } console.log(numbers);

Expected Output

[1, 3, 4, 5]

Practice

Implement Bubble Sort and count how many swaps are performed.

Interview Questions

  1. How does Bubble Sort work?
  2. What is its worst-case complexity?
  3. Is Bubble Sort stable?
  4. When is Bubble Sort useful?