The improved bubble sort

If we subtract the number of passes from the inner loop, we will avoid all the unnecessary comparisons made by the inner loop ({1}):

function modifiedBubbleSort(array, compareFn = defaultCompare) {  const { length } = array;  for (let i = 0; i < length; i++) {    for (let j = 0; j < length - 1 - i; j++) { // {1}      if (compareFn(array[j], array[j + 1]) === Compare.BIGGER_THAN) {        swap(array, j, j + 1);      }    }  }  return array;} 

The following diagram exemplifies how the improved bubble sort works:

Note that we did not compare the numbers that are already in place. Even though we made this small change to improve the bubble sort ...

Get Learning JavaScript Data Structures and Algorithms - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.