Intermediate 25 min

Implementation

Let’s code bubble sort. It’s one of the simplest sorting algorithms to implement.

Basic Implementation


              function bubbleSort(arr) {
const n = arr.length;

for (let i = 0; i < n - 1; i++) {
  for (let j = 0; j < n - i - 1; j++) {
    if (arr[j] > arr[j + 1]) {
      // Swap elements
      [arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
    }
  }
}

return arr;
}
            

Try It Yourself

🟨 JavaScript Bubble Sort Implementation
📟 Console Output
Run code to see output...

Code Explanation

  1. Outer loop (i): Runs n-1 times

    • After each iteration, one more element is in place
  2. Inner loop (j): Compares adjacent elements

    • Goes from 0 to n-i-1 (shrinks each pass)
  3. Comparison: arr[j] > arr[j + 1]

    • Checks if elements are out of order
  4. Swap: Exchanges elements if needed

    • Uses destructuring for clean swap

Edge Cases

Handle these scenarios:

  • Empty array: Returns empty array (loops don’t run)
  • Single element: Already sorted, returns as-is
  • Already sorted: Still runs all passes (inefficient)
  • All same values: No swaps needed, but still runs

Optimized Version

We can optimize by stopping early if no swaps occur:

🟨 JavaScript Optimized Bubble Sort
📟 Console Output
Run code to see output...

What’s Next?

Now that you can implement it, let’s analyze its performance and complexity.