Clojure sort and sort-by both promise "Guaranteed to be stable: equal elements will not be reordered."
The current implementations of sort
and sort-by
in ClojureScript are from
9ee4dbf63d3968b70f29708aa03aace98cdcb624
Author: Stuart Halloway <stu@thinkrelevance.com>
AuthorDate: Thu Jul 14 12:18:34 2011 -0500
`
(defn sort
"Returns a sorted sequence of the items in coll. Comp can be
boolean-valued comparison function, or a -/0/+ valued comparator.
Comp defaults to compare."
([coll]
(sort compare coll))
([comp coll]
(if (seq coll)
(let [a (to-array coll)]
;; matching Clojure's stable sort, though docs don't promise it
(garray/stableSort a (fn->comparator comp))
(seq a))
())))
(defn sort-by
"Returns a sorted sequence of the items in coll, where the sort
order is determined by comparing (keyfn item). Comp can be
boolean-valued comparison function, or a -/0/+ valued comparator.
Comp defaults to compare."
([keyfn coll]
(sort-by keyfn compare coll))
([keyfn comp coll]
(sort (fn [x y] ((fn->comparator comp) (keyfn x) (keyfn y))) coll)))
`
Since this implementation has apparently called google's stableSort for the last 8 years perhaps the docstring could be amended to reflect this.
For reference, the google closure array documentation: (link: https://google.github.io/closure-library/api/goog.array.html):
Note that stableSort's docstring actually doesn't mention stability but the sort function contains "This sort is not guaranteed to be stable."