1. 就如同打牌一样的摆牌顺序,从小到大或从大到小依次排列;
    2. 拿到一张牌,我们把最小的放在最左边,所以新接的牌需要和左手边的每一个进行对比,插入到合适的位置;
    3. 由于用splice插入会有很多问题(不只是插入那么简单,其他后面的内容还需要重新排列等等),我们就采取相互之间覆盖挪动来代替插入

    https://jsbin.com/gijoneluce/2/edit?js,console

    1. const insertSort = (a) => {
    2. for(let i = 1; i < a.length; i ++) {
    3. const insert = a[i];
    4. let j;
    5. for( j = i - 1; j >= 0; j --) {
    6. if (insert <= a[j]) {
    7. a[j + 1] = a[j];
    8. } else {
    9. break;
    10. }
    11. a[j] = insert;
    12. }
    13. }
    14. return a;
    15. }
    16. console.log('------------', insertSort([2, 1, 3, 1, 4]))
    17. console.log('--------', insertSort([1,2,9,4,10,20,12]))
    18. // // // // // // [1, 2, 4, 9, 10, 12, 20]
    19. console.log('--------', insertSort([11,2,39,24,1,2,9]))
    20. // // // // // // [1, 2, 2, 9, 11, 24, 39]
    21. console.log('--------', insertSort([]))
    22. // // // // // // []
    23. console.log('--------', insertSort([1,1,1,1,1]))