Sorting algorithms/Heapsort: Difference between revisions
Content added Content deleted
m (→{{header|C}}: use for loops instead of while statements.) |
|||
Line 264: | Line 264: | ||
} |
} |
||
}</lang> |
}</lang> |
||
=={{header|Clojure}}== |
|||
{{trans|OCaml}} |
|||
<lang lisp> |
|||
(defn- swap [a i j] |
|||
(assoc a i (nth a j) j (nth a i))) |
|||
(defn- sift [a pred k l] |
|||
(loop [a a x k y (inc (* 2 k))] |
|||
(if (< (inc (* 2 x)) l) |
|||
(let [ch (if (and (< y (dec l)) (pred (nth a y) (nth a (inc y)))) |
|||
(inc y) |
|||
y)] |
|||
(if (pred (nth a x) (nth a ch)) |
|||
(recur (swap a x ch) ch (inc (* 2 ch))) |
|||
a)) |
|||
a))) |
|||
(defn heapsort |
|||
([a pred] |
|||
(let [len (count a)] |
|||
(reduce (fn [c term] (sift (swap c term 0) pred 0 term)) |
|||
(reduce (fn [c i] (sift c pred i len)) |
|||
(vec a) |
|||
(range (dec (int (/ len 2))) -1 -1)) |
|||
(range (dec len) 0 -1)))) |
|||
([a] |
|||
(heapsort a <))) |
|||
</lang> |
|||
Example usage: |
|||
<lang lisp> |
|||
user> (heapsort [1 2 4 6 2 3 6]) |
|||
[1 2 2 3 4 6 6] |
|||
user> (heapsort [1 2 4 6 2 3 6] >) |
|||
[6 6 4 3 2 2 1] |
|||
user> (heapsort (list 1 2 4 6 2 3 6)) |
|||
[1 2 2 3 4 6 6] |
|||
</lang> |
|||
=={{header|Common Lisp}}== |
=={{header|Common Lisp}}== |