for 循环
const arr = [3, 4, 2, 7, 9, 6, 2, 8, 3, 6, 2, 1, 6, 3, 7, 4, 21, 8, 0, 5]; var i = arr.length - 1, pos = 0; var l = arr.length - 1; while (i) { for (var j = 0; j < arr.length - i - 1; j++) { if (arr[j] > arr[j + 1]) { let tmp = arr[j]; arr[j] = arr[j + 1] arr[j + 1] = tmp; } } i--; } console.log(arr);
while 循环
const arr = [3, 4, 2, 7, 9, 6, 2, 8, 3, 6, 2, 1, 6, 3, 7, 4, 21, 8, 0, 5]; var m = 0; console.time('计时'); for (var j = 0; j < arr.length; j++) { // let flag = true; for (var i = 0; i < arr.length - j - 1; i++) { if (arr[i] > arr[i + 1]) { let tmp = arr[i]; arr[i] = arr[i + 1]; arr[i + 1] = tmp; m++; } } // if (flag) { // break; // } } console.timeEnd('计时'); console.log(arr); console.log(m);