Sort an integer array, keeping first in place

前端 未结 6 817
傲寒
傲寒 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 20:59

    Have a look at below snippet.

    It is really simple. Just remove first element from the arrary into new array.

    Sort rest of the array and check if max of this array is greater than first element.

    If yes, then push it into to result arrary. Otherwise concat rest of the array with result array

    var input1 = [10, 7, 12, 3, 5, 6];
    var expected1 = [10, 12, 3, 5, 6, 7];
    
    var input2 = [12, 8, 5, 9, 6, 10];
    var expected2 = [12, 5, 6, 8, 9, 10];
    
    function customSort(aInput) {
      var aResult = [aInput.shift()];
      aInput = aInput.sort(function(a, b) { return a - b;});
      if (aInput[aInput.length - 1] > aResult[0]) {
        var iMax = aInput.pop();
        aResult.push(iMax);
      }
      aResult = aResult.concat(aInput);
      return aResult;
    }
    
    console.log("Expected: ", expected1.toString());
    console.log("Sorted: ", customSort(input1).toString());
    console.log("Expected: ", expected2.toString());
    console.log("Sorted: ", customSort(input2).toString());

提交回复
热议问题