Sorting
Bubble Sort
Is a sort algorithm by going through the data and comparing the current element with the next element if the current element is larger we swap so we can place the largest element at the end of the dataset and we repeat this process until we have a sorted data set. The video shows how the algorithm works
Big(O)
| | speed | | -------- | ------- | | Best | O(n) | | Average | O(n^2) | | Worst | O(n^2) |
Implementation
function bubbleSort(data){
for(let i = 0; i < data.length; i++){
// the second loop keep iterating until lenght - i -1 because we dont need to include the sorted elements
for(let j = 0; j < data.length -i-1; j++){
if(data[j] > data[j+1]){
let temp = data[j];
data[j] = data[j+1];
data[j+1] = temp;
}
}
}
}