All you have to do to this code is add a -i to the j loop limit to get the better behaviour. That is not significant enough complexity that it should be avoided IMO.
I take back my previous statement. The bubble-sort shown in this graphic doesn't match the algorithm I provided earlier. It matches this one:
function videoSort(array) {
var sorted = false;
while (!sorted) {
sorted = true;
for (var i = 0; i < array.length - 1; ++i) {
if (array[i] > array[i + 1]) {
[array[i], array[i+1]] = [array[i+1], array[i]];
sorted = false;
}
}
}
return array;
}
This is a much more opaque version of the bubble sort algorithm and may-as-well skip the "already sorted section."
function productionSort(array) {
var sorted = false;
var j = 0;
while (!sorted) {
sorted = true;
++j;
for (var i = 0; i < array.length - j; ++i) {
if (array[i] > array[i + 1]) {
[array[i], array[i+1]] = [array[i+1], array[i]];
sorted = false;
}
}
}
return array;
}
So yeah, you're right. If the video isn't using the simplest possible version of the sort, then it might as well color-code the sorted section so you know what's going on.
1
u/IdiotCharizard Dec 03 '19
All you have to do to this code is add a
-ito the j loop limit to get the better behaviour. That is not significant enough complexity that it should be avoided IMO.