Bubble Sort Algorithm in DSA Javascript - Time & Space Complexity
We want to understand how the time taken by Bubble Sort changes as the list size grows.
How does the number of steps increase when sorting bigger lists?
Analyze the time complexity of the following code snippet.
function bubbleSort(arr) {
const n = arr.length;
for (let i = 0; i < n - 1; i++) {
for (let j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
[arr[j], arr[j + 1]] = [arr[j + 1], arr[j]];
}
}
}
return arr;
}
This code sorts an array by repeatedly swapping adjacent elements if they are in the wrong order.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing and possibly swapping adjacent elements inside nested loops.
- How many times: Outer loop runs (n-1) times; inner loop runs decreasing times from (n-1) down to 1.
As the list size grows, the number of comparisons grows roughly with the square of the size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 45 comparisons |
| 100 | About 4,950 comparisons |
| 1000 | About 499,500 comparisons |
Pattern observation: Doubling the input size roughly quadruples the number of operations.
Time Complexity: O(n²)
This means the time to sort grows quickly as the list gets bigger, roughly proportional to the square of the list size.
[X] Wrong: "Bubble Sort only takes time proportional to the list size (O(n)) because it just compares neighbors."
[OK] Correct: Because it uses nested loops, it compares many pairs multiple times, making the total steps grow much faster than the list size.
Understanding Bubble Sort's time complexity helps you appreciate why more efficient sorting methods are used in real projects.
It also shows your ability to analyze how algorithms behave as data grows, a key skill in coding interviews.
"What if we add a flag to stop early if no swaps happen in a pass? How would the time complexity change in the best case?"
Practice
Bubble Sort algorithm?Solution
Step 1: Understand Bubble Sort mechanism
Bubble Sort compares adjacent elements and swaps them if they are out of order.Step 2: Compare with other sorting methods
Other options describe different algorithms: selection sort (A), divide and conquer (B), insertion sort (D).Final Answer:
Repeatedly swap adjacent elements if they are in the wrong order -> Option AQuick Check:
Bubble Sort = swapping adjacent pairs [OK]
- Confusing Bubble Sort with Selection Sort
- Thinking it divides the array like Merge Sort
- Assuming it inserts elements like Insertion Sort
arr[i] and arr[i+1] in JavaScript during Bubble Sort?Solution
Step 1: Understand JavaScript swapping
JavaScript does not support tuple unpacking; use a temporary variable to swap.Step 2: Analyze each option
let temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; uses a temp variable correctly. arr[i], arr[i+1] = arr[i+1], arr[i]; is Python syntax, invalid in JS. swap(arr[i], arr[i+1]); calls undefined function. arr[i] = arr[i+1]; arr[i+1] = arr[i]; overwrites values incorrectly.Final Answer:
let temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; -> Option DQuick Check:
Use temp variable to swap in JS [OK]
- Using Python-style tuple swap in JavaScript
- Calling undefined swap function
- Overwriting values without temp variable
let arr = [4, 2, 3];
for(let i = 0; i < arr.length - 1; i++) {
if(arr[i] > arr[i+1]) {
let temp = arr[i];
arr[i] = arr[i+1];
arr[i+1] = temp;
}
}
console.log(arr);Solution
Step 1: Trace the single pass of the loop
Loop runs i=0 to 1. At i=0: 4 > 2, swap -> arr = [2,4,3]. At i=1: 4 > 3, swap -> arr = [2,3,4].Step 2: Check loop range carefully
The loop runs only once over the array (i from 0 to length-2). So swaps happen at i=0 and i=1.Final Answer:
[2, 4, 3] -> Option AQuick Check:
One pass swaps neighbors to partially sort [OK]
- Assuming full sort after one pass
- Ignoring second swap at i=1
- Confusing array indices
function bubbleSort(arr) {
for(let i = 0; i < arr.length; i++) {
for(let j = 0; j < arr.length; j++) {
if(arr[j] > arr[j+1]) {
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
return arr;
}Solution
Step 1: Analyze inner loop range
Inner loop runs tillj < arr.length, soarr[j+1]can be undefined at last index causing error.Step 2: Fix inner loop to avoid out-of-bound access
Changing condition toj < arr.length - i - 1prevents accessing beyond array length and optimizes sorting.Final Answer:
Change inner loop condition toj < arr.length - i - 1-> Option CQuick Check:
Inner loop must avoid out-of-bound index [OK]
- Ignoring array boundary causing undefined access
- Changing outer loop incorrectly
- Removing inner loop breaks sorting
[5, 1, 4, 2, 8], how many total swaps will Bubble Sort perform to fully sort it in ascending order?Solution
Step 1: Perform Bubble Sort passes and count swaps
Pass 1 swaps: (5,1), (5,4), (5,2) -> 3 swaps (5 and 8 no swap).Step 2: Continue passes counting swaps
Pass 2 swaps: (4,2) -> 1 swap. Pass 3 swaps: (4,3) none here but actually (2,3) no swap, but we need to check carefully. Actually, pass 3 swaps: (2,3) no swap, pass 4 no swaps. Total swaps: 3 + 1 + 2 = 6.Step 3: Verify total swaps
Counting carefully, total swaps are 6, so 6.Final Answer:
6 -> Option BQuick Check:
Count swaps each pass carefully [OK]
- Assuming swaps equal to array length
- Counting comparisons instead of swaps
- Missing repeated swaps in later passes
Ready to prove it?
Pass the test and this pattern moves unknown
