gpt4 book ai didi

javascript - 对整数数组进行排序,保持第一个位置

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:58:30 26 4
gpt4 key购买 nike

我将如何对数组进行如下排序:

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

[12, 8, 5, 9, 6, 10] --> [12, 5, 6, 8, 9, 10]
  • 保持数组[0] 就位
  • 紧随其后的下一个最高整数(如果有的话)
  • 然后从最低的整数开始升序

最佳答案

您可以保存第一个元素的值并在第一个排序增量的条件中使用它。然后按标准增量排序。

它是如何工作的(排序顺序来自 Edge)

              condition  numerical     sortFn
a b delta delta result comment
----- ----- --------- --------- --------- -----------------
7 10* 1 1 different section
12* 7 -1 -1 different section
12* 10* 0 2 2 same section
12* 7 -1 -1 same section
3 7 0 -4 -4 same section
3 12* 1 1 different section
3 7 0 -4 -4 same section
5 7 0 -2 -2 same section
5 12* 1 1 different section
5 3 0 2 2 same section
5 7 0 -2 -2 same section
6 7 0 -1 -1 same section
6 3 0 3 3 same section
6 5 0 1 1 same section
6 7 0 -1 -1 same section

* denotes elements who should be in the first section

Elements of different section means one of the elements goes into the first and the other into the second section, the value is taken by the delta of the condition.

Elements of the same section means, both elements belongs to the same section. For sorting the delta of the values is returned.

function sort(array) {
var first = array[0];
array.sort(function (a, b) {
return (a < first) - (b < first) || a - b;
});
return array;
}

console.log(sort([10, 7, 12, 3, 5, 6]));
console.log(sort([12, 8, 5, 9, 6, 10]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 对整数数组进行排序,保持第一个位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44440357/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com