function bubbleSort (arr) { let len = arr.length; for (let i = 0; i < len - 1; i++) { let swap = false; for (let j = i + 1; j < len; j++) { if (arr[j] < arr[j - 1]) { var temp = arr[j]; arr[j] = arr[j - 1]; arr[j - 1] = temp; swap = true; } } console.log( i + '次:' + arr); if (!swap) { break; } } console.log(arr); } bubbleSort([2,5,3,8,4,5,9,34])