views:

203

answers:

4

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.

+1  A: 

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

01
+4  A: 

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

weiyin
+1 for formal "stable" name
Joel Coehoorn
A: 

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

toddk
function sortInt(a,b) { return (a>b) - (a<b); }
some
A: 

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

olliej