Bubble Sort

Bubble Sort repeatedly steps through the list, comparing adjacent elements and swapping them if they are in the wrong order. It is named for the way smaller or larger elements 'bubble' to the top of the list.

Step 1 / 160
Initial array.
56
70
56
40
59
71
96
59
26
59
53
48
74
52
87
Speed

Time Complexity

Best CaseO(n)
Average CaseO(n²)
Worst CaseO(n²)

Space Complexity

Worst CaseO(1)
Space complexity refers to the total amount of memory space used by an algorithm, including the space of input values for execution.

Implementation

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);
}