REBOL [
    Title:   "Heapsort"
    Author:  "Aldo Calpini"
    Date:    03-Jul-2001
    File:    %heapsort.r
]

IM: 139968
IA:   3877
IC:  29573

LAST: 42

gen_random: func [N] [
    LAST: (LAST * IA + IC) // IM
    return N * LAST / IM
]

heapsort: func [
    n ra
    /local 
        rra [decimal!]
        l [integer!]
        ir [integer!]
        j [integer!]
        k [integer!]
] [
    l: n / 2 + 1
    ir: n
    while [1] [
    
        either l > 1 [
            l: l - 1
            rra: pick ra l
        ] [
            rra: pick ra ir
            v: pick ra 1
            change at ra ir v
            ir: ir - 1
            if [ir = 1] [
                change at ra 1 rra
                return
            ]
        ]
        i: l
        j: l * 2
        
        while [ j <= ir ] [
            if j < ir [
                v1: pick ra j
                v2: pick ra (j + 1)
                if v1 < v2 [
                    j: j + 1
                ]
            ]
            v: pick ra j
            either rra < v [
                change at ra i v
                i: j
                j: j + i
            ] [
                j: ir + 1
            ]
        ]
        change at ra i rra
    ]
]

                

NUM: to-integer to-string system/script/args
NUM: either NUM < 1 [ 1 ] [ NUM ]

ary: copy []
for i 1 NUM 1 [
    insert tail ary gen_random 1
]

heapsort NUM ary

probe ary

v: pick ary NUM

print v
write %output.rebol v