'Why does javascript sort on arrays make different amounts of comparisons?
var arr=[..."12345678"]
var res=[];
var cnt=0;
function comparefn(a,b,c){
var rnd1;
console.log(`a=${a} , b=${b} , arr=${arr}`)
rnd1=Math.random() - 0.5;
res.push(`${++cnt}) (${rnd1}) ${a},${b}` )
return rnd1;
}
console.log(arr.sort(comparefn));
console.log(res.join(", "))
If I change the return value on the compare function (comparefn) then if it was a return of 1 then it would compare 28 times. If the return value of the compare function (comparefn) is 0 (zero) then is only compares it 7 times. Now, if the return value is Math.random() - 0.5 then it compare a variable number of times, from about 7 to 28 (which I suppose is the maximum number of 2 item permutations)? Some strange bits - on MDN is says 'Note: compareFunction(a, b) must always return the same value when given a specific pair of elements a and b as its two arguments. ' I am not sure why it says that, because this function returns a random number (-1 to plus 1 approx) for ANY 2 items. As you may know this is the algo for the quick shuffle on an array (Math.random() - 0.5). I have found though, with 8 items that 0.3 gives a more natural order of items, that is to say that 0.5 used to favour the low numbers being in the start of the array but with 0.3 the array used to start with more different numbers - of course this is just by my eye (it could just be with eight items).
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|