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));
4
  • 1
    I fixed the formatting for you. Please use the preview pane next time. Commented Apr 20, 2011 at 11:22
  • 1
    "How .sort() working" in what way? It sorts. The precise algorithm is probably implementation-defined. What else do you want to know? Commented Apr 20, 2011 at 11:22
  • hi tomalak ,thanks for doing formatting. I want to know which algo is used on .sort() function. Commented Apr 20, 2011 at 11:24
  • 1
    Then your question is a duplicate. Commented Apr 20, 2011 at 11:27

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

-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.

1 Comment

Elements are not converted into numbers. Elements don't change. Expression a-b calculates numerical result, that's all.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.