0

I have ran across some peculiar behavior shown in the fiddle here

I'm sorting a collection in which the property by which I'm sorting is identical for all members in the collection using this function:

var doSort = function(array,key){
    var data = array.sort(function(a,b){
        var x  = a[key],
            y = b[key];
        if(typeof x === 'string'){
            x = x.toLowerCase();
        }
        if(typeof y === 'string'){
            y = y.toLowerCase();
        }

        return ((x > y) ? -1 : ((x < y) ? 1 : 0));
    });
    return (direction === 'asc') ? data : data.reverse();
};

In IE and Firefox the results for the logs are 15, 16, 17. While in Chrome they are 15,2,17. It appears that after the n/2(th) element. Technically, the sort is working correctly because the collection is correctly sorted. I'm trying to gain some insight into the differences between Chrome and IE/Firefox.

wootscootinboogie
  • 8,461
  • 33
  • 112
  • 197
  • The spec does not require the `.sort()` algorithm to be a stable sort. – Pointy Nov 05 '14 at 19:15
  • @Pointy I figured as much on that front, I'm just looking for some intuition has to why chrome consistently behaves differently than IE and Firefox, specifically at the n/2(th) element in the collection. – wootscootinboogie Nov 05 '14 at 19:17
  • 1
    Well I guess it implements the sort differently. They're probably all quicksorts, so maybe the V8 one chooses its pivot differently. – Pointy Nov 05 '14 at 19:19
  • @Teemu it looks to me that the array is split in half and when the first element of the second half of the array is compared against the first, Chrome goes ahead and says insert here, at the beginning. Now why the [2] index is messed up as well, that's a total mystery. – wootscootinboogie Nov 05 '14 at 19:30
  • 1
    according to the ecma: "[...] The sort is not necessarily stable (that is, elements that compare equal do not necessarily remain in their original order). [...]" - http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.11 – lloiser Nov 05 '14 at 20:24

0 Answers0