Sreehari
Sreehari

Reputation: 515

How does the sort() work in javascript?

var numArray = [4,2,5,3];
numArray.sort(function(a,b){
  console.log("a:" + a + ", b:" + b);
  return a-b;
});

The three possible return numbers are: <0 (less than 0), 0, or >0 (greater than 0):

 Less than 0: Sort "a" to be a lower index than "b"
 Zero: "a" and "b" should be considered equal, and no sorting performed.
 Greater than 0: Sort "b" to be a lower index than "a".

I am getting like this on console

    a:4, b:2
    a:4, b:5
    a:5, b:3
    a:2, b:3
    a:4, b:3
    [2, 3, 4, 5]

May I know how the values of a and b are getting changed as seen above?

In the first step a=4 and b=2. In this case it will swap. then the array becomes [2,4,5,3];

In the second step a=4 and b=5. In this case the items remains same. then the array becomes [2,4,5,3];

In the third step a=5 and b=3. In this case it will swap. then the array becomes [2,4,3,5];

Until this step it is okay. But after that how the value of a and b becomes 2 and 3 > respectively instead of 2 and 4.

Anyone can help me?

Thanks in advance

Upvotes: 2

Views: 304

Answers (1)

Mark Byers
Mark Byers

Reputation: 838096

There is no guarantee that the sort method uses a simple compare and swap algorithm.

More likely your browser uses something like merge sort, but the specific algorithm will depend on the browser and version.

Since Firefox is open source you can see how sort is implemented by checking the source code. It uses a merge sort.

Upvotes: 2

Related Questions