Sorting algorithms/Heapsort: Difference between revisions

m
no edit summary
No edit summary
mNo edit summary
Line 2,910:
acdhijkqw</lang>
 
=={{header|Janetetet}}==
Translation of [https://gist.github.com/Techcable/c411b3a550e252b1fd681e1fc1734174 this] Python code. Based on R. Sedgwick's Algorithms Section 2.4.
 
Although Janet is a (functional) Lisp, it has support for [https://janet-lang.org/docs/data_structures/arrays.html mutable arrays] and imperative programming.
 
<lang janet>(defn swap [l a b]
(defn swap [l a b]
(let [aval (get l a) bval (get l b)]
(put l a bval)
Line 2,947 ⟶ 2,948:
(def val (get heap idx))
(def parent-idx (parent idx))
(ifwhen (and (not (nil? parent-idx)) (< val (get heap parent-idx))) (do
(swap heap parent-idx idx)
(swim parent-idx)
))
(check-invariants idx))
Line 2,969 ⟶ 2,970:
(= 1 (length smaller-children)) (get smaller-children 0)
(< (get heap (get smaller-children 0)) (get heap (get smaller-children 1))) (get smaller-children 0)
# NOTE: `true` is used instead ofThe `else` for final branch inof `cond` is implicit
true (get smaller-children 1)
))
(if (notunless (nil? smallest-child)) (do
(swap heap smallest-child idx)
(sink smallest-child)
# Recheck invariants
(check-invariants idx))))
 
(defn insert [val]
Line 2,987 ⟶ 2,988:
(def largest (get heap ROOT))
(def new-root (array/pop heap))
(ifwhen (> (length heap) 1) (do
(put heap ROOT new-root)
(sink ROOT)))
(assert (not (nil? largest)))
largest)
Anonymous user