Sort an integer array, keeping first in place

前端 未结 6 802
傲寒
傲寒 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

    An easy solution could be to sort the entire array and then partition the resulting array on basis of your initial first element.

    I.e.

    • first sort [10, 7, 12, 3] to [3, 7, 10, 12]
    • then split it into >= 10 and < 10: [10, 12] and [3, 7]
    • and finally combine both to [10, 12, 3, 7]

    Sample implementation without polish:

    function customSort(input) {
      var firstElem = input[0];
      var sortedInput = input.sort(function(a, b) { return a-b; });
      var firstElemPos = sortedInput.indexOf(firstElem);
      var greaterEqualsFirstElem = sortedInput.splice(firstElemPos);
      var lessThanFirstElem = sortedInput.splice(0, firstElemPos);
      return greaterEqualsFirstElem.concat(lessThanFirstElem);
    }
    
    console.log(customSort([10, 7, 12, 3, 5, 6]));
    console.log(customSort([12, 8, 5, 9, 6, 10]));
    console.log(customSort([12, 8, 5, 9, 12, 6, 10]));
    console.log(customSort([12]));
    console.log(customSort([]));

提交回复
热议问题