Basically, sorting works by comparing two elements at a time. The comparison is more than logical - you have three options: less, equal, and more. In JavaScript, these three values ββare represented by n <0, 0, and n> 0, respectively.
In other words, negative numbers mean a < b
; 0
means a = b
and positive values a > b
.
To answer a broader question: there are several relatively fast algorithms for sorting a list by comparing its elements. The most popular is Quicksort ; however, Quicksort is unstable, so some engines (Firefox for sure) use a different algorithm. Simple stable view of Mergesort .
Sorting algorithms are often one of the first algorithms analyzed in intro CS classes, because they are simple, but still interesting and non-trivial, to illustrate how to analyze the algorithms in general. You should read about them for this reason and simply because they are pretty cool.
Slightly random aside:
You could also imagine using a special type (such as an enumeration) for this kind of thing. For example, a comparison function may return LT
, GT
or EQ
, if necessary. However, in a dynamic language such as JavaScript, it is much easier to use numbers. In languages ββmore obsessed with types (like Haskell :)), using a special order type makes more sense.
Tikhon jelvis
source share