sorting - How does the sort() work in javascript? -


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

the 3 possible return numbers are: <0 (less 0), 0, or >0 (greater 0):

 less 0: sort "a" lower index "b"  zero: "a" , "b" should considered equal, , no sorting performed.  greater 0: sort "b" lower index "a". 

i getting 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 know how values of , b getting changed seen above?

in first step a=4 , b=2. in case swap. array becomes [2,4,5,3];

in second step a=4 , b=5. in case items remains same. array becomes [2,4,5,3];

in third step a=5 , b=3. in case swap. array becomes [2,4,3,5];

until step okay. after how value of , b becomes 2 , 3 > respectively instead of 2 , 4.

anyone can me?

thanks in advance

there no guarantee sort method uses simple compare , swap algorithm.

more browser uses merge sort, specific algorithm depend on browser , version.

since firefox open source can see how sort implemented checking source code. uses merge sort.


Comments

Popular posts from this blog

c# - SVN Error : "svnadmin: E205000: Too many arguments" -

c++ - Using OpenSSL in a multi-threaded application -

All overlapping substrings matching a java regex -