- 就如同打牌一样的摆牌顺序,从小到大或从大到小依次排列;
- 拿到一张牌,我们把最小的放在最左边,所以新接的牌需要和左手边的每一个进行对比,插入到合适的位置;
- 由于用splice插入会有很多问题(不只是插入那么简单,其他后面的内容还需要重新排列等等),我们就采取相互之间覆盖挪动来代替插入
https://jsbin.com/gijoneluce/2/edit?js,console
const insertSort = (a) => {for(let i = 1; i < a.length; i ++) {const insert = a[i];let j;for( j = i - 1; j >= 0; j --) {if (insert <= a[j]) {a[j + 1] = a[j];} else {break;}a[j] = insert;}}return a;}console.log('------------', insertSort([2, 1, 3, 1, 4]))console.log('--------', insertSort([1,2,9,4,10,20,12]))// // // // // // [1, 2, 4, 9, 10, 12, 20]console.log('--------', insertSort([11,2,39,24,1,2,9]))// // // // // // [1, 2, 2, 9, 11, 24, 39]console.log('--------', insertSort([]))// // // // // // []console.log('--------', insertSort([1,1,1,1,1]))
