0

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));
Community
  • 1
  • 1
Hitesh Prajapati
  • 2,762
  • 8
  • 23
  • 29

3 Answers3

2

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.

Community
  • 1
  • 1
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
0

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.

pepkin88
  • 2,742
  • 20
  • 19
-1

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.

KebdnK
  • 555
  • 1
  • 6
  • 23
  • Elements are not converted into numbers. Elements don't change. Expression `a-b` calculates numerical result, that's all. – pepkin88 Apr 20 '11 at 11:42