bubblesort
bubblesort copied to clipboard
Convert code from insertion sort logic to bubble sort
Collection elements should bubble up to the right in a bubble sort. The compares should be made with all elements to the right. In an insertion sort elements will sink towards the left and compares are made with all elements to the left.
Please see step by step compares: https://en.wikipedia.org/wiki/Bubble_sort
@addyosmani Comparing two different approaches. Please have a look at this screenshot - https://www.dropbox.com/s/zljbhl2m5n39blj/Screenshot%202016-12-23%2016.48.07.png?dl=0
function bSort(arr) {
var temp, ctr = 0, n = arr.length;
for (var i = 0; i < n - 1; i++) {
var swapped = false;
for (var j = 0; j < n - i - 1; j++) {
if (arr[j] > arr[j + 1]) {
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
swapped = true;
}
++ctr;
}
if (!swapped) break;
}
console.log('Total Iterations: ', ctr);
return arr;
}