Jump to content

Sort numerical array.


Recommended Posts

Hi there!!W3schools has demonstrated how to sort a numerical array using the following code: <code><script type="text/javascript">function sortNumber(a, B){return a -b;}var arr = new Array(6);arr[0] = "10";arr[1] = "5";arr[2] = "40";arr[3] = "25";arr[4] = "1000";arr[5] = "1";document.write(arr + "<br />");document.write(arr.sort(sortNumber));</script></code>I just wanted to know how does the sortNumber() function work? What's the meaningful of the a,b parameters which are passed into the function? What are they intended to represent, and how does this snippet: a-b cause to sort the array numerical elements ascending?

Link to post
Share on other sites

Given any pair of elements in the array, if the return value is positive, A goes after B, if the return value is negative, A goes before B. If the return value is 0 their positions are not changed.

  • Like 1
Link to post
Share on other sites

@ingolme:Thanks you very much about your response, but unfortunately, I didn't understand your words because you spoke too shortly. I didn't understand how does the a and b parameters that passed into the sortNumber() function represent an index in the array. Here they don't use the arr syntax so how can they access to the array's indices?

Edited by atar
Link to post
Share on other sites

All of it happend inside the Javascript's engine.The sort() method takes the function you gave it and tries it on pairs of elements over and over until all of them are sorted. You tell it which of the pair is supposed to go first an which goes second with the algorithm you have in the function. Just imagine that the array only has two elements, A points to the first element and B points to the last one, you tell it which of the two should go first based on the value that they have.

  • Like 1
Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...