Bird
Raised Fist0
DSA Javascriptprogramming

Bubble Sort Algorithm in DSA Javascript

Choose your learning style10 modes available
Mental Model
Bubble sort compares pairs of neighbors and swaps them if they are in the wrong order, pushing the largest unsorted value to the end each pass.
Analogy: Imagine bubbles rising in water: the biggest bubble slowly moves up to the surface by swapping places with smaller bubbles below it.
Array: [5, 3, 8, 4, 2]
Indexes:  0   1   2   3   4
Dry Run Walkthrough
Input: list: [5, 3, 8, 4, 2]
Goal: Sort the list in ascending order using bubble sort
Step 1: Compare 5 and 3, swap because 5 > 3
[3, 5, 8, 4, 2]
Why: Swap to move larger number rightwards
Step 2: Compare 5 and 8, no swap because 5 < 8
[3, 5, 8, 4, 2]
Why: Numbers in correct order, no change
Step 3: Compare 8 and 4, swap because 8 > 4
[3, 5, 4, 8, 2]
Why: Move larger number 8 rightwards
Step 4: Compare 8 and 2, swap because 8 > 2
[3, 5, 4, 2, 8]
Why: Largest number 8 bubbles to the end
Step 5: Start second pass: compare 3 and 5, no swap
[3, 5, 4, 2, 8]
Why: First two numbers in order
Step 6: Compare 5 and 4, swap because 5 > 4
[3, 4, 5, 2, 8]
Why: Move 5 rightwards
Step 7: Compare 5 and 2, swap because 5 > 2
[3, 4, 2, 5, 8]
Why: Move 5 rightwards
Step 8: Start third pass: compare 3 and 4, no swap
[3, 4, 2, 5, 8]
Why: Numbers in order
Step 9: Compare 4 and 2, swap because 4 > 2
[3, 2, 4, 5, 8]
Why: Move 4 rightwards
Step 10: Start fourth pass: compare 3 and 2, swap because 3 > 2
[2, 3, 4, 5, 8]
Why: Move smaller number leftwards
Result:
Final sorted array: [2, 3, 4, 5, 8]
Annotated Code
DSA Javascript
class BubbleSort {
  static sort(arr) {
    let n = arr.length;
    for (let i = 0; i < n - 1; i++) {
      // Each pass pushes largest unsorted to end
      for (let j = 0; j < n - 1 - i; j++) {
        if (arr[j] > arr[j + 1]) {
          // Swap if left is bigger
          let temp = arr[j];
          arr[j] = arr[j + 1];
          arr[j + 1] = temp;
        }
      }
    }
    return arr;
  }
}

// Driver code
const input = [5, 3, 8, 4, 2];
const sorted = BubbleSort.sort(input);
console.log(sorted);
for (let i = 0; i < n - 1; i++) {
outer loop controls number of passes
for (let j = 0; j < n - 1 - i; j++) {
inner loop compares adjacent pairs, shrinking range each pass
if (arr[j] > arr[j + 1]) {
compare neighbors to decide if swap needed
let temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp;
swap to move larger number rightwards
OutputSuccess
[2, 3, 4, 5, 8]
Complexity Analysis
Time: O(n^2) because each element is compared multiple times in nested loops
Space: O(1) because sorting is done in place without extra storage
vs Alternative: Compared to more advanced sorts like quicksort (O(n log n)), bubble sort is slower but simpler to understand
Edge Cases
empty array []
returns empty array immediately without error
DSA Javascript
for (let i = 0; i < n - 1; i++) {
array with one element [7]
returns the same single-element array unchanged
DSA Javascript
for (let i = 0; i < n - 1; i++) {
array with all equal elements [2, 2, 2]
no swaps occur, returns same array
DSA Javascript
if (arr[j] > arr[j + 1]) {
When to Use This Pattern
When you see a problem asking to sort by repeatedly swapping neighbors until sorted, think of bubble sort because it pushes largest values to the end step-by-step.
Common Mistakes
Mistake: Not reducing inner loop range each pass, causing unnecessary comparisons
Fix: Use 'n - 1 - i' as inner loop limit to avoid checking already sorted tail
Mistake: Swapping incorrectly or forgetting to swap neighbors
Fix: Always swap arr[j] and arr[j+1] when arr[j] > arr[j+1]
Summary
Bubble sort repeatedly swaps adjacent elements to sort an array in ascending order.
Use bubble sort for small or nearly sorted lists when simplicity matters more than speed.
The key insight is that each pass moves the largest unsorted element to its correct position at the end.

Practice

(1/5)
1. What is the main idea behind the Bubble Sort algorithm?
easy
A. Repeatedly swap adjacent elements if they are in the wrong order
B. Divide the array into halves and sort each half separately
C. Select the smallest element and place it at the beginning
D. Insert each element into its correct position in a sorted sublist

Solution

  1. Step 1: Understand Bubble Sort mechanism

    Bubble Sort compares adjacent elements and swaps them if they are out of order.
  2. Step 2: Compare with other sorting methods

    Other options describe different algorithms: selection sort (A), divide and conquer (B), insertion sort (D).
  3. Final Answer:

    Repeatedly swap adjacent elements if they are in the wrong order -> Option A
  4. Quick Check:

    Bubble Sort = swapping adjacent pairs [OK]
Hint: Bubble Sort swaps neighbors repeatedly to sort [OK]
Common Mistakes:
  • Confusing Bubble Sort with Selection Sort
  • Thinking it divides the array like Merge Sort
  • Assuming it inserts elements like Insertion Sort
2. Which of the following is the correct syntax to swap two elements arr[i] and arr[i+1] in JavaScript during Bubble Sort?
easy
A. arr[i] = arr[i+1]; arr[i+1] = arr[i];
B. arr[i], arr[i+1] = arr[i+1], arr[i];
C. swap(arr[i], arr[i+1]);
D. let temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp;

Solution

  1. Step 1: Understand JavaScript swapping

    JavaScript does not support tuple unpacking; use a temporary variable to swap.
  2. 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.
  3. Final Answer:

    let temp = arr[i]; arr[i] = arr[i+1]; arr[i+1] = temp; -> Option D
  4. Quick Check:

    Use temp variable to swap in JS [OK]
Hint: Use temp variable to swap in JavaScript [OK]
Common Mistakes:
  • Using Python-style tuple swap in JavaScript
  • Calling undefined swap function
  • Overwriting values without temp variable
3. What will be the output of the following JavaScript code snippet?
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);
medium
A. [2, 4, 3]
B. [2, 3, 4]
C. [4, 2, 3]
D. [3, 2, 4]

Solution

  1. 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].
  2. 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.
  3. Final Answer:

    [2, 4, 3] -> Option A
  4. Quick Check:

    One pass swaps neighbors to partially sort [OK]
Hint: Trace each swap carefully for one loop pass [OK]
Common Mistakes:
  • Assuming full sort after one pass
  • Ignoring second swap at i=1
  • Confusing array indices
4. Identify the error in this Bubble Sort code snippet and choose the correct fix:
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;
}
medium
A. Remove the inner loop completely
B. Change outer loop to run from i = 1 to arr.length
C. Change inner loop condition to j < arr.length - i - 1
D. Add a check to skip swapping equal elements

Solution

  1. Step 1: Analyze inner loop range

    Inner loop runs till j < arr.length, so arr[j+1] can be undefined at last index causing error.
  2. Step 2: Fix inner loop to avoid out-of-bound access

    Changing condition to j < arr.length - i - 1 prevents accessing beyond array length and optimizes sorting.
  3. Final Answer:

    Change inner loop condition to j < arr.length - i - 1 -> Option C
  4. Quick Check:

    Inner loop must avoid out-of-bound index [OK]
Hint: Inner loop stops earlier each pass to avoid overflow [OK]
Common Mistakes:
  • Ignoring array boundary causing undefined access
  • Changing outer loop incorrectly
  • Removing inner loop breaks sorting
5. Given the array [5, 1, 4, 2, 8], how many total swaps will Bubble Sort perform to fully sort it in ascending order?
hard
A. 4
B. 6
C. 5
D. 7

Solution

  1. 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).
  2. 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.
  3. Step 3: Verify total swaps

    Counting carefully, total swaps are 6, so 6.
  4. Final Answer:

    6 -> Option B
  5. Quick Check:

    Count swaps each pass carefully [OK]
Hint: Count swaps pass by pass to avoid missing any [OK]
Common Mistakes:
  • Assuming swaps equal to array length
  • Counting comparisons instead of swaps
  • Missing repeated swaps in later passes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard