JSFiddle - React, Tailwind, and code Playground
JavaScript
var times = 0;
function ascending(a, b) {return a - b;}
function swap(list, i, j) {
var ele = list[i];
list[i] = list[j];
list[j] = ele;
}
function bubbleTo(list, to, compare) {
var swapornot = 0;
for(var i = 0; i < to - 1; i++) {
if(compare(list[i + 1], list[i]) < 0) {
swap(list, i + 1, i);
swapornot = 1;
}
}
times++;
return swapornot;
}
function bubbleSort(list, compare) {
for(var i = 0; i < list.length; i++) {
var swap = bubbleTo(list, list.length - i, compare);
//if(!swap)
// break;
}
}
var list = [10, 9, 1, 2, 5, 3, 8, 7];
bubbleSort(list, ascending);
console.log(list);
console.log(times);