Created
June 6, 2018 13:54
-
-
Save alphaKAI/72d19156da7ba0f3d7a80930a53d9bf9 to your computer and use it in GitHub Desktop.
Heap-sort in OCaml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let swap a i j = | |
let t = a.(i) in | |
a.(i) <- a.(j); | |
a.(j) <- t;; | |
let printArray arr = | |
Printf.printf "["; | |
for idx = 0 to Array.length arr - 1 do | |
if idx > 0 then Printf.printf ", "; | |
Printf.printf "%d" @@ Array.get arr idx | |
done; | |
Printf.printf "]\n";; | |
let rec shift_down a i n = | |
let left = i * 2 + 1 in | |
let right = i * 2 + 2 in | |
let max_idx_left = if left < n && a.(left) > a.(i) then left else i in | |
let max_idx = if right < n && a.(right) > a.(max_idx_left) then right else max_idx_left in | |
if max_idx != i then | |
begin | |
swap a max_idx i; | |
shift_down a max_idx n | |
end;; | |
let build_heap a n = | |
for i = (n - 1) / 2 downto 0 do | |
shift_down a i n | |
done;; | |
let heap_sort a n = | |
build_heap a n; | |
for i = n - 1 downto 1 do | |
swap a 0 i; | |
shift_down a 0 i; | |
done;; | |
let () = | |
let x = [|5;4;6;2;1;6|] in | |
printArray x; | |
heap_sort x 6; | |
printArray x;; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment