I decided to get shuffled values from array. for that i used this function, i got it from net, it works fine. But i don\'t know, how it\'s works...
any one can help me t
This code is using the supplied rand
function as the comparison operator for the Array.Sort
method (http://msdn.microsoft.com/en-us/library/4b4fbfhk(VS.85).aspx). Since the Math.random (http://msdn.microsoft.com/en-us/library/41336409.aspx) function returns a value from 0 (inclusive) to 1 (exclusive), the rand
function will return a value from 0.5 (inclusive) to -0.5 (exclusive).
Normally the sortFunction supplied to the Sort
method takes 2 arguments that are compared. The sortFunction compares them and returns a value that means:
As the sort
method runs, it uses this comparison to determine which array values should go before the others.
In the case of your code, the rand
function's return value is random and has no correlation to the data. This means that, whenever the sort
function tries to compare two values in the array, half of the time it will say the first item is less than the second and half the second item will be less than the first. As this is done over the entire length of the array, items are swapped randomly and the whole array becomes randomized.
array.sort() has an optional parameter that is a sorting function, you can pass a function reference to change the order of the array.
Maybe this page can be helpful http://www.javascriptkit.com/javatutors/arraysort.shtml