April 2018
Beginner to intermediate
426 pages
10h 19m
English
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 ...