2
var anArray = [ 5, 4, 8 , 1, 3] ; 

anArray.sort(function (a,b){return a - b}); 

1) Can someone run me through how JavaScript will execute the sort method with function that is passed as a parameter ?

  • It will compare 5 with 4 then because it's positive, 4 will be before 5. Then it will compare 5 with every other number but 1 and 3 are also smaller than 5. So how java script know which position to put them before 5?

  • then it will compare 4 with every other number and 8 with every other number etc... how java script do this? I want to do it with pen and paper.

2) why the function that is passed as an parameter is nameless ?

thank you.

Vitf
  • 27
  • 4
  • 1
    In most cases merge sort or quick sort is used which are faster (`nlogn` running time).. – Sampath Liyanage Jan 01 '15 at 17:16
  • 1
    [Here is a Wikipedia article to get you started with how sorting works.](http://en.wikipedia.org/wiki/Sorting_algorithm) The precise algorithm used for JavaScript is not stipulated by the specification. – Pointy Jan 01 '15 at 17:21

1 Answers1

3
  1. Exactly how the comparator function will be called — that is, the sequence of values passed in — is not defined by the specification of the language. It completely depends on the particular JavaScript implementation and (probably) on the values in the array being sorted. Suffice to say that the sorting algorithm calls your function when it wants to compare two numbers, and that's that.

    The function is expected to return a value that's negative, zero, or positive, indicating that the ordering of the two numbers should be that the first one comes first, that either can come first, or that the second one should come first. A quick way to do that is to just subtract the second number from the first.

  2. The function in your sample code is an anonymous function. It needs no name because it will be bound to a symbol in the receiving function as a result of the function call itself. You can give the function a name if you want to.

Pointy
  • 405,095
  • 59
  • 585
  • 614