Comparing adjacent element and swap - JavaScript?

Bubble sort is a simple sorting algorithm that compares adjacent elements and swaps them if they are in the wrong order. This process repeats until the array is sorted.

How Bubble Sort Works

The algorithm repeatedly steps through the array, compares adjacent elements, and swaps them if they are in the wrong order. Each pass "bubbles" the largest element to its correct position.

Bubble Sort Process Initial: 10 30 5 40 Compare & Swap: 10 5 30 40 After sorting: 5 10 30 40

Basic Bubble Sort Implementation

Here's a simple bubble sort implementation that sorts an array in ascending order:

var numbers = [10, 100, 30, 40, 90, 4, 91, 56, 78];

function bubbleSort(arr) {
    for (var i = 0; i  arr[j + 1]) {
                // Swap if they're in wrong order
                var temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            }
        }
    }
    return arr;
}

console.log("Original array:", numbers);
console.log("Sorted array:", bubbleSort([...numbers])); // Using spread to avoid modifying original
Original array: [
  10, 100, 30,  40, 90,
   4,  91, 56, 78
]
Sorted array: [
   4, 10, 30, 40, 56,
  78, 90, 91, 100
]

Optimized Bubble Sort

We can optimize bubble sort by stopping early if no swaps occur in a pass, indicating the array is already sorted:

function optimizedBubbleSort(arr) {
    var n = arr.length;
    var swapped;
    
    for (var i = 0; i  arr[j + 1]) {
                // Swap elements
                var temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                swapped = true;
            }
        }
        
        // If no swaps occurred, array is sorted
        if (!swapped) {
            console.log("Array sorted after", i + 1, "passes");
            break;
        }
    }
    
    return arr;
}

var testArray = [5, 2, 8, 1, 9];
console.log("Sorted:", optimizedBubbleSort([...testArray]));
Array sorted after 4 passes
Sorted: [ 1, 2, 5, 8, 9 ]

Step-by-Step Visualization

Let's trace through a small example to see how bubble sort works:

function bubbleSortWithSteps(arr) {
    console.log("Starting array:", arr);
    var steps = 0;
    
    for (var i = 0; i  arr[j + 1]) {
                // Swap
                var temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                console.log(`  Swapped! Array now: [${arr.join(', ')}]`);
            } else {
                console.log(`  No swap needed`);
            }
        }
    }
    
    return arr;
}

var smallArray = [4, 2, 7, 1];
bubbleSortWithSteps(smallArray);
Starting array: [ 4, 2, 7, 1 ]

Pass 1:
Step 1: Comparing 4 and 2
  Swapped! Array now: [2, 4, 7, 1]
Step 2: Comparing 4 and 7
  No swap needed
Step 3: Comparing 7 and 1
  Swapped! Array now: [2, 4, 1, 7]

Pass 2:
Step 4: Comparing 2 and 4
  No swap needed
Step 5: Comparing 4 and 1
  Swapped! Array now: [2, 1, 4, 7]

Pass 3:
Step 6: Comparing 2 and 1
  Swapped! Array now: [1, 2, 4, 7]

Time Complexity

Case Time Complexity Description
Best Case O(n) Array is already sorted (with optimization)
Average Case O(n²) Random order array
Worst Case O(n²) Array sorted in reverse order

Conclusion

Bubble sort compares adjacent elements and swaps them if they're in wrong order. While easy to understand, it's inefficient for large datasets with O(n²) complexity. Use it primarily for educational purposes or very small arrays.

Updated on: 2026-03-15T23:19:00+05:30

456 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements