Bhupi
Bhupi

Reputation: 2969

Need to understand Javascript Array.sort() function

This might be a very basic question but I am not able to understand this so please help me to understand how the Javascript's Array.sort() function is working here. I need to understand the dry run of the code:

var x = new Array(5,4,3,78,7,66,5,444,7,8,9,33,4,5,666,1);
console.log("Before = "+ x);
x.sort(
function(a, b){
    var m = a-b;
        console.log(a+" - "+b+" = "+m);
        return m;
    }
);
console.log("After = "+ x);

When I run the above code I found the output as follows: (Here are the few lines of output)

5 - 1 = 4 
1 - 7 = -6 
5 - 7 = -2 
3 - 5 = -2 
78 - 5 = 73 
666 - 5 = 661
etc....

And finally it printed the sorted array in ascending order:

After = 1,3,4,4,5,5,5,7,7,8,9,33,66,78,444,666 

Please let me know how it is picking up the values for "a" and "b" and how it is doing all operation.

Upvotes: 1

Views: 392

Answers (1)

Marc Fischer
Marc Fischer

Reputation: 1306

There is a wide range of sort algorithms, but all (probably just most) need a way to compare two elements.

Compare functions in most languages work like this. When the return Value is positive, the second value is smaller and when the return value is negative the first value is smaller. If it is zero, they are the same.

Which actual sort algorithm Javascript uses might vary from implementation to implementation and it could probably use multiple different algorithms in one implementation or even one sort.

Also see Javascript Array.sort implementation?

Upvotes: 2

Related Questions