cluster1
cluster1

Reputation: 5674

Unexpected behaviour of Javascript Array.sort()

I've tried to sort an array of integers ascending. For understanding the behaviour of the sort-method I've put a console.log in the callback-function:

var field = [50, 90, 1, 10, 2];

console.log(field.join(' | '));
var i = 0

field.sort(function(a, b) { 
    console.log(++i + 'a: ' + a + ', b: ' + b);

    if (a === b) {
        return 0;
    } else if (a > b) {
        return 1;
    } else {
        return -1;
    }                   
});

console.log(field.join(' | '));

Result of the console.log:

PROTOKOLL: 50 | 90 | 1 | 10 | 2 
PROTOKOLL: 1 a: 90, b: 50 
PROTOKOLL: 2 a: 1, b: 90 
PROTOKOLL: 3 a: 1, b: 50 
PROTOKOLL: 4 a: 10, b: 90 
PROTOKOLL: 5 a: 10, b: 50 
PROTOKOLL: 6 a: 10, b: 1 
PROTOKOLL: 7 a: 2, b: 90 
PROTOKOLL: 8 a: 2, b: 10 
PROTOKOLL: 9 a: 2, b: 1 
PROTOKOLL: 1 | 2 | 10 | 50 | 90

After all I know about the Array.sort() method the result should be: a: 50, b: 90 ... but it's the other way.

Can anyone explain it?

Upvotes: 0

Views: 138

Answers (2)

Alexander R.
Alexander R.

Reputation: 1756

It's depends of implementation. In IE 11 you get output as:

50 | 90 | 1 | 10 | 2
1a: 90, b: 50
2a: 1, b: 90
3a: 1, b: 50
4a: 10, b: 90
5a: 10, b: 50
6a: 10, b: 1
7a: 2, b: 90
8a: 2, b: 10
9a: 2, b: 1
1 | 2 | 10 | 50 | 90

In Chrome you'll get:

50 | 90 | 1 | 10 | 2
1a: 50, b: 90
2a: 90, b: 1
3a: 50, b: 1
4a: 90, b: 10
5a: 50, b: 10
6a: 1, b: 10
7a: 90, b: 2
8a: 50, b: 2
9a: 10, b: 2
10a: 1, b: 2
1 | 2 | 10 | 50 | 90

But in Firefox you'll get:

50 | 90 | 1 | 10 | 2
1a: 50, b: 90
2a: 90, b: 1
3a: 50, b: 1
4a: 10, b: 2
5a: 90, b: 2
6a: 1, b: 2
7a: 50, b: 2
8a: 50, b: 10
1 | 2 | 10 | 50 | 90

Pay attention to number of steps. Final results are the same. The internal implementation is different.

Upvotes: 1

Kram
Kram

Reputation: 526

It works like that. Always take the second number and check if it in the right place:

Diagram:

1) 90 > 50 ----> No change
2) now check the second and third number 90 < 1 ---> 1 and 90 swap.
3) check if the first number is lesser than the new second number(1) - 50 < 1 - swap again 50 and 1.
4) 1 is the first number in the array, so go back to 90 and check the number after 90. 

And it is continue like this. OK?

Upvotes: 1

Related Questions