JavaScript: Implement the Bubble Sort Algorithm

1. Introduction

Bubble sort is a simple sorting algorithm that works by repeatedly stepping through the list, comparing each pair of adjacent items, and swapping them if they are in the wrong order. Despite its simplicity, it's generally not the most efficient way to sort large lists, but it's a good starting point for understanding sorting algorithms.

2. Program Overview

In this tutorial:

1. We'll initialize an array of numbers.

2. Implement the Bubble Sort algorithm to sort the array in ascending order.

3. Display the sorted array.

3. Code Program

let numbers = [64, 34, 25, 12, 22, 11, 90];  // An unsorted array

// Implementing the Bubble Sort algorithm
function bubbleSort(arr) {
    let 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]) {
                // Swapping the elements if they are in the wrong order
                let temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
    return arr;  // Returning the sorted array
}

let sortedArray = bubbleSort(numbers);  // Sorting the numbers array using the bubbleSort function

console.log("Sorted array:", sortedArray);

Output:

Sorted array: [11, 12, 22, 25, 34, 64, 90]

4. Step By Step Explanation

1. Array Initialization: We start with unsorted array numbers.

2. Bubble Sort Implementation:

- The outer loop runs n-1 times, where n is the length of the array. This is because the largest element is always moved to its correct position in each iteration.

- The inner loop is responsible for comparing adjacent elements. For every iteration of the outer loop, the inner loop runs n-i-1 times. The value of i corresponds to the number of sorted elements at the end of the array.

- Inside the inner loop, we check if the current element (arr[j]) is greater than the next element (arr[j+1]). If it is, we swap them. This process effectively "bubbles up" the largest unsorted value to its correct position.

3. Displaying the Result: After sorting the array using our bubbleSort function, we display the sorted array using console.log.

Comments