开发者

How .sort () work in JavaScript? [duplicate]

开发者 https://www.devze.com 2023-02-27 14:57 出处:网络
This question already has a开发者_高级运维nswers here: Closed 11 years ago. Possible Duplicate: Javascript Array.sort implementation?
This question already has a开发者_高级运维nswers here: Closed 11 years ago.

Possible Duplicate:

Javascript Array.sort implementation?

I want to know how .sort() works in JavaScript. What algorithm does it use?

function sortNumber(a, b) {
   return a-b;
}

var n = ["1", "5", "40", "2", "9", "3"];
document.write(n.sort(sortNumber));


This question was answered here.

Mozilla uses merge sort, Webkit uses selection sort, and IE is closed-source so hard to tell.

The language specification states no requirement on what algorithm an implementation uses, and your code shouldn't really care about it too much.


Number of comparisons for 100 element test array:

Safari 5 - 541
Opera 11.10 - 586
Firefox 4 - 601
IE 9 - 618
Chrome 9 - 783

And for 1000 element test array:

Safari 5 - 8700
Firefox 4 - 8998
Opera 11.10 - 9137
IE 9 - 11055
Chrome 9 - 11536

It does not describe an algorithm but still shows some interesting data.


in Firefox 4 the elements are converted into Numbers and sorted this way. In your case this is ascending order.

I didn't test it in other browsers so far.

0

精彩评论

暂无评论...
验证码 换一张
取 消