Skip to content

Bubble Sort Guide

S
skipPro
10/2/2026 · 4 views

Bubble sort is an easy to understand sorting method that allows you to sort data numerically or alphabetically.

const numbers = [5,7,2,3,5,7,3,5,3,7,2,8,0,2,3,0,5,2,7,1,3,7,9,3]

function orderNumbers(array) {
    // Define unsorted
    let unsorted = false
    // Bubble Sort will need to run through the array an indetermined amount of times, but at the minimum, once. This makes a do/while loop the best choice
    do {
        unsorted = false
        // Every number excluding the last index of an array will be checked so we can check it with the index after
        for (let i = 0; i < array.length - 1; i++) {

            let num1 = array[i]
            let num2 = array[i + 1]

            // This compares the two numbers, if number 1 is greater than number 2, this means that they are not in the right order and need to be swapped. This also means that the array is not fully sorted
            if (num1 > num2) {
                array.splice(i, 2, num2, num1)
                unsorted = true
            }
        }
        console.log(array)
        // If the for loop above runs completely and did not need to make any changes, unsorted will equal false and the do/while loop will end
    } while (unsorted);
    console.log(unsorted)
    console.log("ARRAY SORTED")
}
orderNumbers(numbers)

Enjoy!

hint hint: look up localeCompare()

Comments

Log in to leave a comment.