Nicholas M. Salvatore

Back arrow

Algorithms: Bubble Sort


Bubble sort works by looping through each number in an array, checking if the number after it is greater than it, and swapping positions if it's not.


// initialize array
// loop through array
    // for each number in the array, check if next number is smaller
    // if the next number is smaller, swap positions


An important thing to understand here is that for each iteration, the largest number in that iteration will "bubble" up to the top or end of the array. Because of this, on each iteration, we should subtract the iteration number or index number from the length of the array in our loop condition because we already know that the number at the last index is the largest. Furthermore, we should subtract 1 from the condition since our check will fail if no next number exists.

const nums = [1, 3, 2, 6, 4, 5]

for (let i = 0; i < nums.length; i++) {
    for (let j = 0; i < nums.length - 1 - i; j++) {
        if (nums[j] > nums[j + 1]) {
            const temp = nums[j];
            nums[j] = nums[j + 1];
            nums[j + 1] = temp