我在尝试对 JavaScript 数组进行排序时遇到了一个奇怪的行为。
var arr = ['a', 'b', 'C', 'd', 'e', 'f', 'g', 'h', 'I', 'k'];
arr.sort(function (a, b) {
console.log(a, b);
if (a.length < b.length) return 1;
else if (a.length > b.length) return -1;
else return 0;
});
在这种情况下工作正常,返回相同的数组。
控制台是这样的,
但是当我尝试下面的输入时,
var arr = ['a', 'b', 'C', 'd', 'e', 'f', 'g', 'h', 'I', 'k', 'l'];
给我这个,
我不太明白为什么会这样。
附言。我正在编写此自定义排序检查元素的长度,因为我需要一个其元素根据长度排序的数组。
ECMAScript neither dictates a specific algorithm, nor expects it to be stable (Array.prototype.sort
). Stable sorting algorithms maintain the relative order of elements that appear to be "the same". To Array#sort two items appear the same when the comparison function returns 0. While InsertionSort and MergeSort (Apple and Mozilla) are stable, QuickSort (Google Chrome) is not (Issue 90). Chrome will sort arrays using InsertionSort if the array has 10 or less elements.
So Safari and Firefox will sort ["sed", "dolor", "ipsum", "foo", "bar", "cat", "sit", "man", "lorem", "amet", "maecennas"]
(by character length) in a way that "sed" will retain first position, while Chrome will roll the dice and possibly prefer "cat" to take the pole position. The Chrome developers obviously like Kittens…
因此,如果您发现自己有需要,请自己实现一个稳定的算法,例如 MergeSort。
查看完整帖子 here