1
0
mirror of https://github.com/janet-lang/janet synced 2024-11-28 19:19:53 +00:00

Merge pull request #545 from felixr/master

Revert my buggy hybrid sort
This commit is contained in:
Calvin Rose 2021-01-03 16:39:23 -06:00 committed by GitHub
commit 81f62b246c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -774,27 +774,11 @@
a a
(if (not= (> b a) (> b c)) b c))) (if (not= (> b a) (> b c)) b c)))
(defn- insertion-sort [a lo hi by] (defn sort-help [a lo hi by]
(for i (+ lo 1) (+ hi 1)
(def temp (in a i))
(var j (- i 1))
(while (and (>= j lo) (by temp (in a j)))
(set (a (+ j 1)) (in a j))
(-- j))
(set (a (+ j 1)) temp))
a)
(defn sort
"Sort an array in-place. Uses quick-sort and is not a stable sort."
[a &opt by]
(default by <)
(def stack @[[0 (- (length a) 1)]])
(while (not (empty? stack))
(def [lo hi] (array/pop stack))
(when (< lo hi) (when (< lo hi)
(when (< (- hi lo) 32) (insertion-sort a lo hi by) (break)) (def pivot
(def pivot (median-of-three (in a hi) (in a lo) (in a (math/floor (/ (+ lo hi) 2))))) (median-of-three (in a hi) (in a lo)
(in a (math/floor (/ (+ lo hi) 2)))))
(var left lo) (var left lo)
(var right hi) (var right hi)
(while true (while true
@ -807,12 +791,17 @@
(++ left) (++ left)
(-- right)) (-- right))
(if (>= left right) (break))) (if (>= left right) (break)))
(array/push stack [lo right]) (sort-help a lo right by)
(array/push stack [left hi]))) (sort-help a left hi by))
a) a)
(defn sort
"Sort an array in-place. Uses quick-sort and is not a stable sort."
[a &opt by]
(sort-help a 0 (- (length a) 1) (or by <)))
(undef median-of-three) (undef median-of-three)
(undef insertion-sort) (undef sort-help)
(defn sort-by (defn sort-by
`Returns a new sorted array that compares elements by invoking `Returns a new sorted array that compares elements by invoking