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)):

enter image description here

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)

  • As far as I know, in JS you can always omit the parameters of the function and take them from the arguments. But this is inconvenient, therefore, they write the parameters explicitly in order to emphasize how many of them there will be (in fact, this is a matter of code style, not more). You understand the principle correctly, but be careful with such sortings, in a number of languages ​​you will get something different from what you are expecting, since the comparison operator must be antisymmetric, transitive and anti-reflective. - pavel

1 answer 1

"but everything works the same way" - where does it work? The array is not sorted. Such a compare function returns a random result, after the "sorting", the elements in the array will be in random order.

 var arr = [1, 2, 3, 4, 5]; var count = 0; function compareRandom() { count++; return Math.random() - 0.5; } arr.sort(compareRandom); console.log(count); console.log( arr ); 

Note the changing value of count . Theoretically, such a "sorting" may never end, since two comparisons of the same pair of numbers may give opposite results.

And, on points:

  1. Yes, you understand correctly.
  2. Yes, you can not specify.

 var arr = [1, 2, 3, 4, 5]; var count = 0; function compareNumeric(a, b) { count++; return a - b; } arr.sort(compareNumeric); console.log(count); console.log( arr ); 

During normal (with compareNumeric ) array sorting, you must perform a certain number of comparisons of pairs of elements. Depending on the initial arrangement of the elements in the array, some pairs will be compared several times. The sorting logic is based on the fact that repeated comparisons of numbers 2 and 3 return a result indicating that three are more than two. If the result of these repeated comparisons is random, then how are the numbers 2 and 3 to end up in the final sorted array?

  • Yes, in the textbook, in the assignment, the task was just that the elements of the array after the sorting went in random order (about this, I added to my question). About the count I did not quite understand; the fact that the counter is changing there is clear to me, but in order to understand why it is changing apparently and you need to study the "universal sorting algorithm" implemented inside the JavaScript interpreter itself, right? and apparently this is a separate issue. - Alexander Kazakov
  • два сравнения одной и той же пары чисел могут дать противоположные результаты - no one compares the same numbers again (except bogosort), there is no need to double-check the comparison algorithm. The number of comparisons varies, because in fact these are different inputs, numbers correspond to different weights. Shuffle the array before sorting and inspect the number of comparisons in the second snippet. - vp_arth