Sort an integer array, keeping first in place

前端 未结 6 816
傲寒
傲寒 2020-12-19 20:21

How would I sort arrays as follows:

[10, 7, 12, 3, 5, 6] --> [10, 12, 3, 5, 6, 7]

[12, 8, 5, 9, 6, 10] --> [12, 5, 6, 8, 9, 10] 
    <
6条回答
  •  情书的邮戳
    2020-12-19 21:13

    My proposal is based on:

    • reduce original array into two containing the lower and upper numbers to the first one
    • sort each array and concatenate

    In this way the initial problem is divided in two sub problems that are more simple to work on.

    function cSort(arr) {
        var retval = arr.reduce(function (acc, val) {
            acc[(val < arr[0]) ? 1 : 0].push(val);
            return acc;
        }, [[], []]);
        return retval[0].sort((a, b) => a-b).concat(retval[1].sort((a, b) => a-b));
    }
    
    //
    //  test
    //
    console.log(cSort([10, 7, 12, 3, 5, 6]));
    console.log(cSort([12, 8, 5, 9, 6, 10]));
    console.log(cSort([12, 8, 5, 9, 12, 6, 10]));
    console.log(cSort([12]));
    console.log(cSort([]));

提交回复
热议问题