# $Id: heapsort.pliant,v 1.0 2002/02/07 15:44:00 dada Exp $
# http://dada.perl.it/shootout/

module "/pliant/language/context.pli"

gvar Int IM := 139968
gvar Int IA :=   3877
gvar Int IC :=  29573

gvar Int LAST := 42

function gen_random n -> r
  arg Float n ; arg Float r
  LAST := (LAST * IA + IC) % IM
  r := (n * LAST) / IM
  return r

function heapsort n ra
  arg Int n ; arg_rw Array:Float ra
  var Float rra
  var Int i
  var Int j
  var Int l := (n\2) + 1
  var Int ir := n
  
  part heapsort_loop
    if l>1
      l := l - 1
      rra := ra:l
    else
      rra := ra:ir
      ra:ir := ra:1
      ir := ir - 1
      if ir=1
        ra:1 := rra
        leave heapsort_loop
    i := l
    j := l*2

    while j<=ir
      if j<ir and ra:j < ra:(j+1)
        j := j + 1
      if rra < ra:j
        ra:i := ra:j
        i := j
        j := j + i
      else
        j := ir + 1
    ra:i := rra
    restart heapsort_loop

gvar Float result 

gvar Int i

gvar Array:Float ary

gvar Str s_n := cast ((pliant_script_args translate Address 1) map CStr) Str
if (s_n parse (gvar Int n))
  for (i) 1 n
    ary += gen_random(1.0)
  heapsort n-1 ary
  console (string ary:(ary:size-1) "fixed 9") eol
else
  console "usage: heapsort.pliant <number>" eol