本文介绍了对整数数组进行排序,保持原位的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我如何按如下方式对数组进行排序:
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]
- 保持数组[0]到位
- 下一个最高整数(如果有的话)
- 然后从最低整数<升序 推荐答案
您可以保存第一个元素的值并在第一个元素的条件下使用它排序三角洲。然后按标准增量排序。
You could save the value of the first element and use it in a condition for the first sorting delta. Then sort by the standard delta.
工作原理(排序顺序来自Edge)
How it works (the sort order is from 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; }
更多推荐
对整数数组进行排序,保持原位
发布评论