# JavaScript Algorithms: Sort a list using Bubble Sort in 2022

Last updated: Jul 1, 2022

Bubble Sort also known as sinking sort is one of the simplest algorithm for sorting, but inefficient with a complexity of O(n^2).

## Algorithm:

• Loop through an array,
• Compares each pair of adjacent elements. Keep comparing one element to the one right next to it,
• Swaps them if they are in the wrong order. If the element on the right is smaller, we swap the two positions.
• Repeat the process until no swaps are required, implies the list is sorted.
`````` function swapElement(arr, firstIndex, secondIndex){
var tmp = arr[firstIndex];
arr[firstIndex] = arr[secondIndex];
arr[secondIndex] = tmp;
}

function bubbleSort(arr){

var len = arr.length,
i, j, stop;

for (i = 0; i < len; i++){
for (j = 0, stop = len-i; j < stop; j++){
if (arr[j] > arr[j+1]){
swapElement(arr, j, j+1);
}
}
}

return arr;
}
console.log(bubbleSort([30, 3, 90, 150, 45, 63, 27, 18, 12, 999]));``````

## Code Explanation

• We start with the first element, then compare it with the second. Here, it’s 30 and 3.
• If the first is greater than the second, then we swap them, else no change. Since 30 > 3, therefore we need to swap. New array will looks like, `[3, 30, 90, 150, 45, 63, 27, 18, 12, 999]`
• Now switch to the second element of the array. Compare 30 and 90
• Compare it with the third element. And continue the process.

## Step by step Explanation by w3resource:

As it’s clear from the algorithm that we are looping the array 2 times, due to a check whether we need to swap the item with the one on the right or not and this leads to the order of complexity to `O(N^2)`. An inefficient sorting implementation.