- 本质上是选择排序,选择排序是从左到右一个一个比较,把小的放在前面;冒泡排序的的比较方式不同;
- 冒泡排序是从左到右将相邻的进行排序,大的放到最右边。
https://jsbin.com/zojesuxuxa/edit?js,console
const bubbleSort = (a) => {for(let i = 0; i < a.length - 1; i++) {for(let j = i + 1; j < a.length; j ++) {if (a[i] > a[j]) {[a[i], a[j]] = [a[j], a[i]];}}}return a;}console.log('------------', bubbleSort([2, 1, 3, 1, 4]))console.log('--------', bubbleSort([1,2,9,4,10,20,12]))// // // // // [1, 2, 4, 9, 10, 12, 20]console.log('--------', bubbleSort([11,2,39,24,1,2,9]))// // // // // [1, 2, 2, 9, 11, 24, 39]console.log('--------', bubbleSort([]))// // // // // []console.log('--------', bubbleSort([1,1,1,1,1]))
