Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the JavaScript sort function work(as an algorithm)? [duplicate]

The JavaScript sort function which takes a parameter allows one to pass in a function.

For example:

var myarray=[25, 8, 7, 41]
myarray.sort(function(a,b){return a - b}) //Array now becomes [7, 8, 25, 41]

How is it that the code

function(a,b){
    return a - b
}

is interpreted to be ascending? It's supposed to be divided into three cases, < 0 , == 0, and > 0, but how does this make sense when a and b can be anything?

Thank You!

like image 202
Caffeinated Avatar asked Mar 22 '12 22:03

Caffeinated


1 Answers

The reason answering your question is especially tricky, or at least in detail, is because there is no specification that says which sorting algorithm a browser should implement. So telling you specifically how it works on one browser may differ between browsers, or even change over time.

The gist of it is though, you want to think of "a" and "b" as being any two values. If you are returning the result of "a" - "b", then your sort goes in ascending order. If you do "b" - "a", then it is in descending order.

The neat thing about making your own sort functions, is that you can compare the value of "a" and "b" after processing them in a separate function. So lets say you want to sort by the Celsius values, but your array in only in Fahrenheit. You can do something like:

.sort(function(a,b){ return to_fahrenheit(a) - to_fahrenheit(b);}
like image 96
GoldenNewby Avatar answered Oct 31 '22 20:10

GoldenNewby