How does Math.random work to sort an array?

I had learned about the sort method, but got stuck at the random sorting part.
I know we can use this:
array.sort (function(a, b) {
return 0.5 - Math.random()});
to create a random sorted array, but how does it work?

This is what I know so far:

array.sort(function(a, b){return a - b});
it will sort the array from small number to bigger number,
it’s because the value which a - b returns is negative, so the smaller number will be in the front.

vice versa,
array.sort(function(a, b){return b - a});
the value which b - a returns is positive, so the bigger number will be in the front.

But here comes the question,
Math.random() can create number between 0~1 (excluded),
which means the result of 0.5 - Math.random() could be either a positive or negative value.
Then, why it can create many different arrays instead of just ascending and descending one?

for example, this array [40,100,10,5,1,25]
how does it become like [100,40,5,1,10,25] or [5,40,1,100,25,10] by using the method of Math.random?

1 Like

If compareFunction is supplied, the array elements are sorted according to the return value of the compare function. If a and b are two elements being compared, then:

  1. If compareFunction(a, b) is less than 0, sort a to an index lower than b, i.e. a comes first.
  2. If compareFunction(a, b) returns 0, leave a and b unchanged with respect to each other, but sorted with respect to all different elements. Note: the ECMAscript standard does not guarantee this behaviour, and thus not all browsers (e.g. Mozilla versions dating back to at least 2003) respect this.
  3. If compareFunction(a, b) is greater than 0, sort b to a lower index than a.

compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. If inconsistent results are returned then the sort order is undefined.

So you’re just returning a random positive or negative number when you compare every two elements in turn, and JS will sort randomly. Each comparison is either positive or negative (very occasionally it will be 0 as well), so it will not be just ascending or descending most of the time, it will be random. You’re ignoring what the actual values in the array are, you’re just randomly returning < 0, 0 or > 0 for every pair that gets compared

1 Like

Math.random returns a random number between 0 and 1. So if it happens to give you a number less then 0.5 then you get a negative number and if it’s over that then you get a positive.

2 Likes

Thank you so much! I didn’t realize that the comparision happens more than just one time and each time with different arguement due to Math.random,
now I know how it works, and finally can move on to other methods. Thank you.

1 Like

hi everyone,

I,ve been lookink fo hours for an explanation of :

array.sort (function(a, b) {
return 0.5 - Math.random()});

I get that Math.random() returns a number from 0 up to but not including 1, but I don´t understand the point of it in the randomization formula and when added the -0.5 it gets much more confusing for me.

Can someone do manually what the function does with a simple arrray like this one :

var simpleArray = [3,9,1];

Please explain how Math.random() -0.5 affects the result.

I need that someone explains steb by step the function, in other words what is the logic behind it.

I will thank forever to anyone who could clarify this.

If the function you pass to sort is the ‘compare function’ and if it’s less than 0, element a goes first, otherwise element b goes first.

0.5 - Math.random() will give you random numbers that are roughly 50% negative and 50% positive.

1 Like

than you for your answer r1chard5mith I already know that because as i said i spent hours reading posts theory and explanations: my doubt is as follows:

  1. I really dont get how: return Math.random()-0.5; (which can return values between -0.5 and 0.49999) causes var myA = [3,9,1]; to shuffle the numbers in the array myA,

  2. . Also when I think of numbers between ( -0.5 and 0.49999 ) I dont think of 3,9,1… I think of -0.2, 0.2, .-01, 0.1.

I still think my answer is unresponded.

Doesn’t that explain it? If you get a negative value, they go in order a,b, otherwise they go in order b,a - so they get ‘shuffled’.

In this case, the values returned by the function have nothing to do with the actual elements of the array.

Sorry for mi insistence but it does not explain it : I gave a very especific escenario and also asked how return Math.random()-0.5; can affect the randomness of causes var myA = [3,9,1]; I am not askinf for a abstract explanation , but for my scenario so i can understant how the formula works and taking into consideration that i know all this :

Math.random() returns a random number between 0 and 1 (0 is inclusive, but 1 is not).

By subtracting 0.5 from the value returned by Math.random(), you are essentially changing the range of the returned value.

For the smallest value that Math.random() returns (0) you will get -0.5. And for the maximum value (0.9999…) you will get (0.4999…).

The code Math.random() - 0.5 will return such numbers, but you are using it inside the compare function of the sort method, so all that the code does is randomly (re)arrange the array.

it still does not make sense how the Math.random()-0.5 arranges the arrays.

Start with the array [3,9,1]

If the random function returns a negative number, the 3 and the 9 stay in the same order ie; you have [3,9,1]

BUT if the random function returns a positive number, then they go in the opposite order (b comes first) ie; you now have [9,3,1]

Then repeat the process for the next pair of elements, which will either be 9,1 or 3,1 depending on the result of the first sort. If the next random number is negative, swap them. If it’s positive, don’t swap them.

The sole determinant of whether the elements are swapped or not is the return value of the compare function.

4 Likes

Thank you so much, your explanation is excellent, now i get it - i was blocked and frustrated-, but only one last doubt remains:

what is the need for the -0.5 ? why not 0.7 or 8?

I think I get it the 0.5 controls the randomness. Is that correct?

0.5 is chosen just so that half of the time the result will be less than zero and half the time it will be greater than zero.

1 Like

thank you r1chard5mith for not giving up in your effort to make me understand. the example makes it crystal clear .I see how internaly the function retrieves a random number with Math.random() and through array.sort (function(a, b) compares two numbers and sorts their index depending on the result being positive negative or 0.

1 Like