Bubble sort is a simple comparison-based algorithm, in which each pair of adjacent elements is compared and the elements are swapped if they are not in order.

function bubbleSort(arr) {
    let swapped;
    do {
        swapped = false
        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;
                swapped = true
            }
        }
    } while (swapped)
    return arr
}
  • First, swapped is set to false inside of the while loop.
  • The for loop checks if each element arr[i] is less than the element to its right arr[i+1].
  • If arr[i] is less than arr[i+1], nothing changes and the loop moves to the next index.
  • If arr[i] is greater than arr[i+1], the two elements swap places.
  • swapped is set to true each time a swap is made.
  • Once the for loop is completed, the while statement checks the value of swapped.
  • If it is true, the while loop will start again from the top.
  • If it's false, then it went through the array without a swap and the array is sorted.
SPEED
2s
Array
[]
Swapped
True