(**************************************************************************)
(*                                                                        *)
(*  Ocamlviz --- real-time profiling tools for Objective Caml             *)
(*  Copyright (C) by INRIA - CNRS - Universite Paris Sud                  *)
(*  Authors: Julien Robert                                                *)
(*           Guillaume Von Tokarski                                       *)
(*           Sylvain Conchon                                              *)
(*           Jean-Christophe Filliatre                                    *)
(*           Fabrice Le Fessant                                           *)
(*  GNU Library General Public License version 2                          *)
(*  See file LICENSE for details                                          *)
(*                                                                        *)
(**************************************************************************)

open Ocamlviz

let swap a i j = let t = a.(i) in a.(i) <- a.(j); a.(j) <- t

let rec downheap a k n = 
  let j = 2 * k+1 in
  if j <= n then
    let j' = if j+1 <= n then if a.(j) < a.(j+1) then j+1 else j else j in
    if a.(k) < a.(j') then begin swap a k j'; downheap a j' n end

let time_downheap = Time.create "downheap"
let downheap a k n =
  Time.start time_downheap;
  downheap a k n;
  Time.stop time_downheap

let heapsort a =
  let n = Array.length a in
  for k = (n-2) / 2 downto 0 do downheap a k (n-1) done;
  for k = n-1 downto 1 do swap a 0 k; downheap a 0 (k-1) done

let time_heapsort = Time.create "heapsort"
let heapsort a =
  Time.start time_heapsort;
  heapsort a;
  Time.stop time_heapsort


let () =
  init ();
  wait_for_connected_clients 1;
  for i = 1 to 10 do
    let a = Array.init 3000000 (fun _ -> Random.int 3000000) in
    heapsort a 
  done

(*
Local Variables: 
compile-command: "unset LANG; make -C .. test-heapsort-byte"
End: 
*)
