Why does sorting a JS array of numbers with < work?

前端 未结 5 1721
一生所求
一生所求 2020-12-06 10:58

When sorting an array of numbers in JavaScript, I accidentally used < instead of the usual - -- but it still works. I wonder why?

Ex

5条回答
  •  有刺的猬
    2020-12-06 11:58

    After my initial comment, I wondered a little bit about how easy it is to find arrays for which this sorting method fails.

    I ran an exhaustive search on arrays of length up to 8 (on an alphabet of size the size of the array), and found nothing. Since my (admittedly shitty) algorithm started to be too slow, I changed it to an alphabet of size 2 and found that binary arrays of length up to 10 are all sorted properly. However, for binary arrays of length 11, many are improperly sorted, for instance [0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0].

    // Check if 'array' is properly sorted using the "<" comparator function
    function sortWorks(array) {
        let sorted_array = array.sort(function(n1, n2) {
            return n1 < n2;
        });
        for (let i=0; i

    I'm getting some weird false-positives for some reason though, not sure where my mistake is.


    EDIT:

    After checking for a little while, here's a partial explanation on why OP's "wrong" sorting method works for lengths <=10 and for lengths >=11: it looks like (at least some) javascript implementations use InsertionSort if the array length is short (length <= 10) and QuickSort otherwise. It looks like QuickSort actively uses the "-1" outputs of the compare function while InsertionSort does not and relies only on the "1" outputs.

    Source: here, all thanks to the original author.

提交回复
热议问题