What is bubble sort?
Bubble sort is an algorithm where the largest value will bubble up to the top of a list, continue sorting this way we will have an ascending sorted array or list. We will use nested loops to compare each current items with the rest of the items in the list.
Understand how to swap two elements using Javascript
//swapping function takes an array, and two indexes
function swap2(arr, index1, index2){
let temp = arr[index1]; //let a temp variable to hold index1's value
arr[index1] = arr[index2]; //replace index1 with index2' value
arr[index2] = temp;//finally replace index2 with temp, which was index1
}
In the ES2015 we can do swapping using this syntax
const swap = (arr, index1, index2) => {
[arr[index1], arr[index2]] = [arr[index2], arr[index1]]
}
Implement bubble sort using nested array - Javascript
Sudo Code:
1.iterate the array reversely
2.create a counter variable
3.iterate the inner loop to compare each item
4.swap the items if the current item is greater
5.when swap happens, set noSwap to false so that it won't break the loop
6.when noSwap never set to false, loop breaks.
function BubbleSort(arr){
for(let i = arr.length; i >0; i--){
let noSwap = true;
for(let j =0; j < (i-1); j++){
if(arr[j] > arr[j+1]){
let temp = arr[j];
arr[j] = arr[j + 1];
arr[j+1]= temp;
noSwap = false;
}
}
if(noSwap){break;}
}
return arr;
}
The time complexity for bubble sort is O(n^2), making it less popular compare to merge sort and other sorting algorithms.
Top comments (0)