2

I suppose it depends on how it's implemented. I'd love it if someone would come back and tell me "yes, in virtually all browsers, order of items will be changed only when necessary to satisfy the conditions of the sort.

4 Answers 4

7

What you're looking for is whether or not the algorithm is "stable". It is known that Firefox's is not, while IE's is. The javascript standard doesn't require a stable sorting algorithm.

Edit: Firefox 3+ has a stable sort. Please see http://www.hedgerwow.com/360/dhtml/js_array_stable_sort.html

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

Comments

1

Every browsers has different implemantation, so dont count on it.

Comments

0

I believe it depends on the type of objects you are sorting within your array. You can supply a "sort function" to array.sort() to determine the rules for sorting a particular object. For example, consider the function:

function sortInt(a, b){
   if ( a < b )
    return -1;
   else if ( a == b )
     return 0;
   else if ( a > b )
     return 1;
}

So this is obviously contrived but you can apply this same type of idea to any object that is "comparable". You will always return a -1, 0, or 1 depending if the a is less than, equal to, or greater than b (respectfully).

You would then say: array.sort(sortInt);

Caveat:

Forgive me if the syntax isn't perfect as I do not have an example on hand. I also am not sure about the stability of Array.sort() from a cross browser perspective.

Edit: Fixed the formatting for the psuedo code snippet

2 Comments

function sortInt(a,b) { return (a>b) - (a<b); }
this does NOT 'preserve' the order of the array where evaluations result in 0. ie array [ a, b, c, d ] does NOT result in identically ordered array when all evaluations result in 0 (on Chrome 26 at least)
0

All the major browsers have stable sorting algorithms, and also (because there is some stupid code out there) they can handle inconsistent compare functions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.