I am studying JavaScript, the sort () method. In general, it was clear, but then I met an example from the tutorial with the Math.random() method:
The task:
Use the sort function to shake up the elements of an array in random order.
Solution (given in the textbook, but without explanation):
The sort function should return a random comparison result. Use Math.random for this.
Usually Math.random () returns a result from 0 to 1. Subtract 0.5 so that the range of values becomes [-0.5 ... 0.5).
var arr = [1, 2, 3, 4, 5]; function compareRandom(a, b) { return Math.random() - 0.5; } arr.sort(compareRandom); alert( arr ); // элементы в случайном порядке, например [3,5,1,2,4]
Long thought. I understand the action given by return Math.random() - 0.5; lines: the "universal sorting algorithm" takes two numbers (a and b), then return Math.random() - 0.5; starts return Math.random() - 0.5; if the number is less than zero , the first in the record is a (sorting will put a at the lower index), if it is greater than zero , the first is in the record b (sorting will put b at the smaller index). To make it clearer, I drew a diagram (for example (2, 4)):
one). My first question is whether I understand correctly the operation of this function. I would also like to know the principle of the "universal sorting algorithm" in accessible language.
// ######
At this stage of the study of JavaScript, I realized that in the function, the values in brackets are passed, and of course they are used in the function itself, here is an example:
function compareNumeric(a, b) { return a - b; } var arr = [ 1, 2, 15 ]; arr.sort(compareNumeric); alert(arr); // 1, 2, 15 But in the first example, in the function, a and b are not used, but immediately comes return , so I tried to completely remove them and wrote this:
var arr = [1, 2, 3, 4, 5]; function compareRandom() { return Math.random() - 0.5; } arr.sort(compareRandom); alert( arr ); Surprisingly, it works and so.
2). My second question is, in this case, you can omit a and b in parentheses at all? Why then in the textbook entry (a, b)
