Bubble Sort also known as sinking sort is one of the simplest algorithm for sorting, but inefficient with a complexity of O(n^2).
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: https://runkit.com/sanmak/javascript-algorithms-sort-a-list-using-bubble-sort
[3, 30, 90, 150, 45, 63, 27, 18, 12, 999]
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.