bubblesort icon indicating copy to clipboard operation
bubblesort copied to clipboard

Convert code from insertion sort logic to bubble sort

Open Dansajjad opened this issue 9 years ago • 1 comments

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

Dansajjad avatar Oct 23 '16 06:10 Dansajjad

@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;
}

softvar avatar Dec 23 '16 11:12 softvar