Sorting algorithms/Heapsort: Difference between revisions

m
→‎{{header|Wren}}: Changed to Wren S/H
m (→‎{{header|Wren}}: Changed to Wren S/H)
 
(121 intermediate revisions by 49 users not shown)
Line 1:
{{task|Sorting Algorithms}} {{Sorting Algorithm}} {{wikipedia|Heapsort}}
{{Sorting Algorithm}}
[[Category:Sorting]]
{{wikipedia|Heapsort}}
{{omit from|GUISS}}
 
[[wp:Heapsort|Heapsort]] is an in-place sorting algorithm with worst case and average complexity of <span style="font-family: serif">O(''n'' log''n'')</span>.
<br>
[[wp:Heapsort|Heapsort]] is an in-place sorting algorithm with worst case and average complexity of &nbsp; <span style="font-family: serif">O(''n'' log''n'')</span>.
 
The basic idea is to turn the array into a binary heap structure, which has the property that it allows efficient retrieval and removal of the maximal element.
 
We repeatedly "remove" the maximal element from the heap, thus building the sorted list from back to front.
 
Heapsort requires random access, so can only be used on an array-like data structure.
A heap sort requires random access, so can only be used on an array-like data structure.
 
Pseudocode:
Line 51 ⟶ 59:
'''else'''
'''return'''
 
<br>
Write a function to sort a collection of integers using heapsort.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<syntaxhighlight lang="11l">F siftdown(&lst, start, end)
V root = start
L
V child = root * 2 + 1
I child > end
L.break
I child + 1 <= end & lst[child] < lst[child + 1]
child++
I lst[root] < lst[child]
swap(&lst[root], &lst[child])
root = child
E
L.break
 
F heapsort(&lst)
L(start) ((lst.len - 2) I/ 2 .. 0).step(-1)
siftdown(&lst, start, lst.len - 1)
 
L(end) (lst.len - 1 .< 0).step(-1)
swap(&lst[end], &lst[0])
siftdown(&lst, 0, end - 1)
 
V arr = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
heapsort(&arr)
print(arr)</syntaxhighlight>
 
{{out}}
<pre>
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
</pre>
 
=={{header|360 Assembly}}==
{{trans|PL/I}}
The program uses ASM structured macros and two ASSIST macros (XDECO, XPRNT) to keep the code as short as possible.
<syntaxhighlight lang="360asm">* Heap sort 22/06/2016
HEAPS CSECT
USING HEAPS,R13 base register
B 72(R15) skip savearea
DC 17F'0' savearea
STM R14,R12,12(R13) prolog
ST R13,4(R15) "
ST R15,8(R13) "
LR R13,R15 "
L R1,N n
BAL R14,HEAPSORT call heapsort(n)
LA R3,PG pgi=0
LA R6,1 i=1
DO WHILE=(C,R6,LE,N) for i=1 to n
LR R1,R6 i
SLA R1,2 .
L R2,A-4(R1) a(i)
XDECO R2,XDEC edit a(i)
MVC 0(4,R3),XDEC+8 output a(i)
LA R3,4(R3) pgi=pgi+4
LA R6,1(R6) i=i+1
ENDDO , end for
XPRNT PG,80 print buffer
L R13,4(0,R13) epilog
LM R14,R12,12(R13) "
XR R15,R15 "
BR R14 exit
PG DC CL80' ' local data
XDEC DS CL12 "
*------- heapsort(icount)----------------------------------------------
HEAPSORT ST R14,SAVEHPSR save return addr
ST R1,ICOUNT icount
BAL R14,HEAPIFY call heapify(icount)
MVC IEND,ICOUNT iend=icount
DO WHILE=(CLC,IEND,GT,=F'1') while iend>1
L R1,IEND iend
LA R2,1 1
BAL R14,SWAP call swap(iend,1)
LA R1,1 1
L R2,IEND iend
BCTR R2,0 -1
ST R2,IEND iend=iend-1
BAL R14,SIFTDOWN call siftdown(1,iend)
ENDDO , end while
L R14,SAVEHPSR restore return addr
BR R14 return to caller
SAVEHPSR DS A local data
ICOUNT DS F "
IEND DS F "
*------- heapify(count)------------------------------------------------
HEAPIFY ST R14,SAVEHPFY save return addr
ST R1,COUNT count
SRA R1,1 /2
ST R1,ISTART istart=count/2
DO WHILE=(C,R1,GE,=F'1') while istart>=1
L R1,ISTART istart
L R2,COUNT count
BAL R14,SIFTDOWN call siftdown(istart,count)
L R1,ISTART istart
BCTR R1,0 -1
ST R1,ISTART istart=istart-1
ENDDO , end while
L R14,SAVEHPFY restore return addr
BR R14 return to caller
SAVEHPFY DS A local data
COUNT DS F "
ISTART DS F "
*------- siftdown(jstart,jend)-----------------------------------------
SIFTDOWN ST R14,SAVESFDW save return addr
ST R1,JSTART jstart
ST R2,JEND jend
ST R1,ROOT root=jstart
LR R3,R1 root
SLA R3,1 root*2
DO WHILE=(C,R3,LE,JEND) while root*2<=jend
ST R3,CHILD child=root*2
MVC SW,ROOT sw=root
L R1,SW sw
SLA R1,2 .
L R2,A-4(R1) a(sw)
L R1,CHILD child
SLA R1,2 .
L R3,A-4(R1) a(child)
IF CR,R2,LT,R3 THEN if a(sw)<a(child) then
MVC SW,CHILD sw=child
ENDIF , end if
L R2,CHILD child
LA R2,1(R2) +1
L R1,SW sw
SLA R1,2 .
L R3,A-4(R1) a(sw)
L R1,CHILD child
LA R1,1(R1) +1
SLA R1,2 .
L R4,A-4(R1) a(child+1)
IF C,R2,LE,JEND,AND, if child+1<=jend and X
CR,R3,LT,R4 THEN a(sw)<a(child+1) then
L R2,CHILD child
LA R2,1(R2) +1
ST R2,SW sw=child+1
ENDIF , end if
IF CLC,SW,NE,ROOT THEN if sw^=root then
L R1,ROOT root
L R2,SW sw
BAL R14,SWAP call swap(root,sw)
MVC ROOT,SW root=sw
ELSE , else
B RETSFDW return
ENDIF , end if
L R3,ROOT root
SLA R3,1 root*2
ENDDO , end while
RETSFDW L R14,SAVESFDW restore return addr
BR R14 return to caller
SAVESFDW DS A local data
JSTART DS F "
ROOT DS F "
JEND DS F "
CHILD DS F "
SW DS F "
*------- swap(x,y)-----------------------------------------------------
SWAP SLA R1,2 x
LA R1,A-4(R1) @a(x)
SLA R2,2 y
LA R2,A-4(R2) @a(y)
L R3,0(R1) temp=a(x)
MVC 0(4,R1),0(R2) a(x)=a(y)
ST R3,0(R2) a(y)=temp
BR R14 return to caller
*------- ------ -------------------------------------------------------
A DC F'4',F'65',F'2',F'-31',F'0',F'99',F'2',F'83',F'782',F'1'
DC F'45',F'82',F'69',F'82',F'104',F'58',F'88',F'112',F'89',F'74'
N DC A((N-A)/L'A) number of items
YREGS
END HEAPS</syntaxhighlight>
{{out}}
<pre>
-31 0 1 2 2 4 45 58 65 69 74 82 82 83 88 89 99 104 112 782
</pre>
 
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program heapSort64.s */
/* look Pseudocode begin this task */
 
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeConstantesARM64.inc"
 
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .asciz "Value : @ \n"
szCarriageReturn: .asciz "\n"
.align 4
//TableNumber: .quad 1,3,6,2,5,9,10,8,4,7
TableNumber: .quad 10,9,8,7,6,-5,4,3,2,1
.equ NBELEMENTS, (. - TableNumber) / 8
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
sZoneConv: .skip 24
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
1:
ldr x0,qAdrTableNumber // address number table
mov x1,#NBELEMENTS // number of élements
bl heapSort
ldr x0,qAdrTableNumber // address number table
bl displayTable
ldr x0,qAdrTableNumber // address number table
mov x1,#NBELEMENTS // number of élements
bl isSorted // control sort
cmp x0,#1 // sorted ?
beq 2f
ldr x0,qAdrszMessSortNok // no !! error sort
bl affichageMess
b 100f
2: // yes
ldr x0,qAdrszMessSortOk
bl affichageMess
100: // standard end of the program
mov x0, #0 // return code
mov x8, #EXIT // request to exit program
svc #0 // perform the system call
qAdrszCarriageReturn: .quad szCarriageReturn
qAdrsMessResult: .quad sMessResult
qAdrTableNumber: .quad TableNumber
qAdrszMessSortOk: .quad szMessSortOk
qAdrszMessSortNok: .quad szMessSortNok
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of elements > 0 */
/* x0 return 0 if not sorted 1 if sorted */
isSorted:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
mov x2,#0
ldr x4,[x0,x2,lsl 3]
1:
add x2,x2,1
cmp x2,x1
bge 99f
ldr x3,[x0,x2, lsl 3]
cmp x3,x4
blt 98f
mov x4,x3
b 1b
98:
mov x0,0 // not sorted
b 100f
99:
mov x0,1 // sorted
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* heap sort */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of element */
heapSort:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
bl heapify // first place table in max-heap order
sub x3,x1,1
1:
cmp x3,0
ble 100f
mov x1,0 // swap the root(maximum value) of the heap with the last element of the heap)
mov x2,x3
bl swapElement
sub x3,x3,1
mov x1,0
mov x2,x3 // put the heap back in max-heap order
bl siftDown
b 1b
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* place table in max-heap order */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the number of element */
heapify:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
str x4,[sp,-16]! // save registers
mov x4,x1
sub x3,x1,2
lsr x3,x3,1
1:
cmp x3,0
blt 100f
mov x1,x3
sub x2,x4,1
bl siftDown
sub x3,x3,1
b 1b
100:
ldr x4,[sp],16 // restaur 1 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* swap two elements of table */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first index */
/* x2 contains the second index */
swapElement:
stp x2,lr,[sp,-16]! // save registers
stp x3,x4,[sp,-16]! // save registers
ldr x3,[x0,x1,lsl #3] // swap number on the table
ldr x4,[x0,x2,lsl #3]
str x4,[x0,x1,lsl #3]
str x3,[x0,x2,lsl #3]
100:
ldp x3,x4,[sp],16 // restaur 2 registers
ldp x2,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* put the heap back in max-heap order */
/******************************************************************/
/* x0 contains the address of table */
/* x1 contains the first index */
/* x2 contains the last index */
siftDown:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
stp x4,x5,[sp,-16]! // save registers
stp x6,x7,[sp,-16]! // save registers
// x1 = root = start
mov x3,x2 // save last index
1:
lsl x4,x1,1
add x4,x4,1
cmp x4,x3
bgt 100f
add x5,x4,1
cmp x5,x3
bgt 2f
ldr x6,[x0,x4,lsl 3] // compare elements on the table
ldr x7,[x0,x5,lsl 3]
cmp x6,x7
csel x4,x5,x4,lt
//movlt x4,x5
2:
ldr x7,[x0,x4,lsl 3] // compare elements on the table
ldr x6,[x0,x1,lsl 3] // root
cmp x6,x7
bge 100f
mov x2,x4 // and x1 is root
bl swapElement
mov x1,x4 // root = child
b 1b
100:
ldp x6,x7,[sp],16 // restaur 2 registers
ldp x4,x5,[sp],16 // restaur 2 registers
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* x0 contains the address of table */
displayTable:
stp x1,lr,[sp,-16]! // save registers
stp x2,x3,[sp,-16]! // save registers
mov x2,x0 // table address
mov x3,0
1: // loop display table
ldr x0,[x2,x3,lsl 3]
ldr x1,qAdrsZoneConv
bl conversion10S // décimal conversion
ldr x0,qAdrsMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at @ character
bl affichageMess // display message
add x3,x3,1
cmp x3,NBELEMENTS - 1
ble 1b
ldr x0,qAdrszCarriageReturn
bl affichageMess
mov x0,x2
100:
ldp x2,x3,[sp],16 // restaur 2 registers
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsZoneConv: .quad sZoneConv
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|Action!}}==
{{Trans|PL/M}}
<syntaxhighlight lang="action!">
;;; HeapSort - tranlsated from the PL/M sample
;;; and using the test cases and test routines from
;;; the Gnome Sort Action! sample (also used in other Action! sort samples)
 
PROC PrintArray(INT ARRAY a INT size)
INT i
Put('[)
FOR i=0 TO size-1
DO
IF i>0 THEN Put(' ) FI
PrintI(a(i))
OD
Put(']) PutE()
RETURN
PROC SiftDown(INT ARRAY a, INT start, endv)
INT root, child, temp
root = start
 
child = (root LSH 1) + 1
WHILE child <= endv DO
IF child + 1 <= endv AND a(child) < a(child+1) THEN child==+ 1 FI
IF a(root) < a(child) THEN
temp = a(root)
a(root) = a(child)
a(child) = temp
root = child
child = (root LSH 1) + 1
ELSE
RETURN
FI
OD
RETURN
 
PROC Heapify(INT ARRAY a, INT count)
INT start
 
start = ((count-2) / 2) + 1
WHILE start <> 0 DO
start = start - 1
SiftDown(a, start, count-1)
OD
RETURN
PROC HeapSort(INT ARRAY a, INT count)
INT endv, temp
Heapify(a, count)
endv = count - 1
WHILE endv > 0 DO
temp = a(0)
a(0) = a(endv)
a(endv) = temp
endv = endv - 1
SiftDown(a, 0, endv)
OD
RETURN
 
PROC Test(INT ARRAY a INT size)
PrintE("Array before sort:")
PrintArray(a,size)
HeapSort(a,size)
PrintE("Array after sort:")
PrintArray(a,size)
PutE()
RETURN
PROC Main()
INT ARRAY
a(10)=[1 4 65535 0 3 7 4 8 20 65530],
b(21)=[10 9 8 7 6 5 4 3 2 1 0
65535 65534 65533 65532 65531
65530 65529 65528 65527 65526],
c(8)=[101 102 103 104 105 106 107 108],
d(12)=[1 65535 1 65535 1 65535 1
65535 1 65535 1 65535]
Test(a,10)
Test(b,21)
Test(c,8)
Test(d,12)
RETURN
</syntaxhighlight>
{{out}}
<pre>
Array before sort:
[1 4 -1 0 3 7 4 8 20 -6]
Array after sort:
[-6 -1 0 1 3 4 4 7 8 20]
 
Array before sort:
[10 9 8 7 6 5 4 3 2 1 0 -1 -2 -3 -4 -5 -6 -7 -8 -9 -10]
Array after sort:
[-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7 8 9 10]
 
Array before sort:
[101 102 103 104 105 106 107 108]
Array after sort:
[101 102 103 104 105 106 107 108]
 
Array before sort:
[1 -1 1 -1 1 -1 1 -1 1 -1 1 -1]
Array after sort:
[-1 -1 -1 -1 -1 -1 1 1 1 1 1 1]
</pre>
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function heapSort(data:Vector.<int>):Vector.<int> {
for (var start:int = (data.length-2)/2; start >= 0; start--) {
siftDown(data, start, data.length);
Line 82 ⟶ 621:
}
}
}</langsyntaxhighlight>
 
=={{header|Ada}}==
This implementation is a generic heapsort for unconstrained arrays.
<langsyntaxhighlight Adalang="ada">generic
type Element_Type is private;
type Index_Type is (<>);
type Collection is array(Index_Type range <>) of Element_Type;
with function "<" (Left, right : element_type) return boolean is <>;
procedure Generic_Heapsort(Item : in out Collection);</langsyntaxhighlight>
<langsyntaxhighlight Adalang="ada">procedure Generic_Heapsort(Item : in out Collection) is
procedure Swap(Left : in out Element_Type; Right : in out Element_Type) is
Temp : Element_Type := Left;
Line 141 ⟶ 680:
end loop;
end Generic_Heapsort;</langsyntaxhighlight>
Demo code:
<langsyntaxhighlight Adalang="ada">with Generic_Heapsort;
with Ada.Text_Io; use Ada.Text_Io;
 
Line 161 ⟶ 700:
end loop;
New_Line;
end Test_Generic_Heapsort;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
<langsyntaxhighlight lang="algol68">#--- Swap function ---#
PROC swap = (REF []INT array, INT first, INT second) VOID:
(
Line 215 ⟶ 754:
print(("After: ", a))
 
)</langsyntaxhighlight>
{{out}}
<pre>
Line 222 ⟶ 761:
After: +136 +326 +494 +633 +720 +760 +784 +813 +972 +980
</pre>
 
=={{header|ALGOL W}}==
{{Trans|PL/M}}
<syntaxhighlight lang="algolw">
begin % heapsort - translated from the PL/M sample %
 
% in-place heapsorts a, a must have bounds 0 :: count - 1 %
procedure heapSort ( integer array a ( * ); integer value count ) ;
begin
procedure siftDown ( integer array a ( * ); integer value start, endv ) ;
begin
integer root, child, temp;
logical done;
root := start;
done := false;
while begin
child := ( root * 2 ) + 1;
child <= endv and not done
end
do begin
if child + 1 <= endv and a( child ) < a( child + 1 ) then child := child + 1;
if a( root ) < a( child ) then begin
temp := a( root );
a( root ) := a( child );
a( child ) := temp;
root := child
end
else done := true
end while_child_le_endv_and_not_done
end siftDown ;
procedure heapify ( integer array a ( * ); integer value count ) ;
begin
integer start;
start := ( count - 2 ) div 2;
while begin
siftDown( a, start, count - 1 );
if start = 0
then false
else begin
start := start - 1;
true
end if_start_eq_0__
end do begin end
end heapify ;
begin % heapSort body %
integer endv, temp;
heapify( a, count );
endv := count - 1;
while endv > 0 do begin
temp := a( 0 );
a( 0 ) := a( endv );
a( endv ) := temp;
endv := endv - 1;
siftDown( a, 0, endv )
end while_endv_gt_0
end heapSortBody
end heapSort;
 
begin % test heapSort %
integer array numbers ( 0 :: 10 );
integer nPos;
% constructy an array of integers and sort it %
nPos := 0;
for v := 4, 65, 2, 31, 0, 99, 2, 8, 3, 782, 1 do begin
numbers( nPos ) := v;
nPos := nPos + 1
end for_v ;
heapSort( numbers, 11 );
% print the sorted array %
for n := 0 until 10 do writeon( i_w := 1, s_w := 0, " ", numbers( n ) )
end tests
end.
</syntaxhighlight>
{{out}}
<pre>
0 1 2 2 3 4 8 31 65 99 782
</pre>
 
=={{header|AppleScript}}==
===Binary heap===
<syntaxhighlight lang="applescript">-- In-place binary heap sort.
-- Heap sort algorithm: J.W.J. Williams.
on heapSort(theList, l, r) -- Sort items l thru r of theList.
set listLen to (count theList)
if (listLen < 2) then return
-- Convert negative and/or transposed range indices.
if (l < 0) then set l to listLen + l + 1
if (r < 0) then set r to listLen + r + 1
if (l > r) then set {l, r} to {r, l}
script o
-- The list as a script property to allow faster references to its items.
property lst : theList
-- In a binary heap, the list index of each node's first child is (node index * 2) - (l - 1). Preset the constant part.
property const : l - 1
-- Private subhandler: sift a value down into the heap from a given node.
on siftDown(siftV, node, endOfHeap)
set child to node * 2 - const
repeat until (child comes after endOfHeap)
set childV to my lst's item child
if (child comes before endOfHeap) then
set child2 to child + 1
set child2V to my lst's item child2
if (child2V > childV) then
set child to child2
set childV to child2V
end if
end if
if (childV > siftV) then
set my lst's item node to childV
set node to child
set child to node * 2 - const
else
exit repeat
end if
end repeat
-- Insert the sifted-down value at the node reached.
set my lst's item node to siftV
end siftDown
end script
-- Arrange the sort range into a "heap" with its "top" at the leftmost position.
repeat with i from (l + r) div 2 to l by -1
tell o to siftDown(its lst's item i, i, r)
end repeat
-- Unpick the heap.
repeat with endOfHeap from r to (l + 1) by -1
set endV to o's lst's item endOfHeap
set o's lst's item endOfHeap to o's lst's item l
tell o to siftDown(endV, l, endOfHeap - 1)
end repeat
return -- nothing
end heapSort
property sort : heapSort
 
-- Demo:
local aList
set aList to {74, 95, 9, 56, 76, 33, 51, 27, 62, 55, 86, 60, 65, 32, 10, 62, 72, 87, 86, 85, 36, 20, 44, 17, 60}
sort(aList, 1, -1) -- Sort items 1 thru -1 of aList.
return aList</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">9, 10, 17, 20, 27, 32, 33, 36, 44, 51, 55, 56, 60, 60, 62, 62, 65, 72, 74, 76, 85, 86, 86, 87, 95}</syntaxhighlight>
 
===Ternary heap===
<syntaxhighlight lang="applescript">-- In-place ternary heap sort.
-- Heap sort algorithm: J.W.J. Williams.
on heapSort(theList, l, r) -- Sort items l thru r of theList.
set listLen to (count theList)
if (listLen < 2) then return
-- Convert negative and/or transposed range indices.
if (l < 0) then set l to listLen + l + 1
if (r < 0) then set r to listLen + r + 1
if (l > r) then set {l, r} to {r, l}
script o
-- The list as a script property to allow faster references to its items.
property lst : theList
-- In a ternary heap, the list index of each node's first child is (node index * 3) - (l * 2 - 1). Preset the constant part.
property const : l * 2 - 1
-- Private subhandler: sift a value down into the heap from a given node.
on siftDown(siftV, node, endOfHeap)
set child to node * 3 - const
repeat until (child comes after endOfHeap)
set childV to my lst's item child
if (child comes before endOfHeap) then
set child2 to child + 1
set child2V to my lst's item child2
if (child2V > childV) then
set child to child2
set childV to child2V
end if
if (child2 comes before endOfHeap) then
set child3 to child2 + 1
set child3V to my lst's item child3
if (child3V > childV) then
set child to child3
set childV to child3V
end if
end if
end if
if (childV > siftV) then
set my lst's item node to childV
set node to child
set child to node * 3 - const
else
exit repeat
end if
end repeat
-- Insert the sifted-down value at the node reached.
set my lst's item node to siftV
end siftDown
end script
-- Arrange the sort range into a ternary "heap" with its "top" at the leftmost position.
repeat with i from (l + r) div 3 to l by -1
tell o to siftDown(its lst's item i, i, r)
end repeat
-- Unpick the heap.
repeat with endOfHeap from r to (l + 1) by -1
set endV to o's lst's item endOfHeap
set o's lst's item endOfHeap to o's lst's item l
tell o to siftDown(endV, l, endOfHeap - 1)
end repeat
return -- nothing
end heapSort
property sort : heapSort
 
-- Demo:
local aList
set aList to {75, 46, 8, 43, 20, 9, 25, 89, 19, 29, 16, 71, 44, 23, 17, 99, 79, 97, 19, 75, 32, 27, 42, 93, 75}
sort(aList, 1, -1) -- Sort items 1 thru -1 of aList.
return aList</syntaxhighlight>
 
{{output}}
<syntaxhighlight lang="applescript">{8, 9, 16, 17, 19, 19, 20, 23, 25, 27, 29, 32, 42, 43, 44, 46, 71, 75, 75, 75, 79, 89, 93, 97, 99}</syntaxhighlight>
 
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
 
/* ARM assembly Raspberry PI */
/* program heapSort.s */
/* look Pseudocode begin this task */
/************************************/
/* Constantes */
/************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessSortOk: .asciz "Table sorted.\n"
szMessSortNok: .asciz "Table not sorted !!!!!.\n"
sMessResult: .ascii "Value : "
sMessValeur: .fill 11, 1, ' ' @ size => 11
szCarriageReturn: .asciz "\n"
.align 4
iGraine: .int 123456
.equ NBELEMENTS, 10
TableNumber: .int 1,3,6,2,5,9,10,8,4,7
#TableNumber: .int 10,9,8,7,6,5,4,3,2,1
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
1:
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl heapSort
ldr r0,iAdrTableNumber @ address number table
bl displayTable
ldr r0,iAdrTableNumber @ address number table
mov r1,#NBELEMENTS @ number of élements
bl isSorted @ control sort
cmp r0,#1 @ sorted ?
beq 2f
ldr r0,iAdrszMessSortNok @ no !! error sort
bl affichageMess
b 100f
2: @ yes
ldr r0,iAdrszMessSortOk
bl affichageMess
100: @ standard end of the program
mov r0, #0 @ return code
mov r7, #EXIT @ request to exit program
svc #0 @ perform the system call
iAdrsMessValeur: .int sMessValeur
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsMessResult: .int sMessResult
iAdrTableNumber: .int TableNumber
iAdrszMessSortOk: .int szMessSortOk
iAdrszMessSortNok: .int szMessSortNok
/******************************************************************/
/* control sorted table */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the number of elements > 0 */
/* r0 return 0 if not sorted 1 if sorted */
isSorted:
push {r2-r4,lr} @ save registers
mov r2,#0
ldr r4,[r0,r2,lsl #2]
1:
add r2,#1
cmp r2,r1
movge r0,#1
bge 100f
ldr r3,[r0,r2, lsl #2]
cmp r3,r4
movlt r0,#0
blt 100f
mov r4,r3
b 1b
100:
pop {r2-r4,lr}
bx lr @ return
/******************************************************************/
/* heap sort */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the number of element */
heapSort:
push {r2,r3,r4,lr} @ save registers
bl heapify @ first place table in max-heap order
sub r3,r1,#1
1:
cmp r3,#0
ble 100f
mov r1,#0 @ swap the root(maximum value) of the heap with the last element of the heap)
mov r2,r3
bl swapElement
sub r3,#1
mov r1,#0
mov r2,r3 @ put the heap back in max-heap order
bl siftDown
b 1b
 
100:
pop {r2,r3,r4,lr}
bx lr @ return
/******************************************************************/
/* place table in max-heap order */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the number of element */
heapify:
push {r1,r2,r3,r4,lr} @ save registers
mov r4,r1
sub r3,r1,#2
lsr r3,#1
1:
cmp r3,#0
blt 100f
mov r1,r3
sub r2,r4,#1
bl siftDown
sub r3,#1
b 1b
100:
pop {r1,r2,r3,r4,lr}
bx lr @ return
/******************************************************************/
/* swap two elements of table */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first index */
/* r2 contains the second index */
swapElement:
push {r3,r4,lr} @ save registers
ldr r3,[r0,r1,lsl #2] @ swap number on the table
ldr r4,[r0,r2,lsl #2]
str r4,[r0,r1,lsl #2]
str r3,[r0,r2,lsl #2]
 
100:
pop {r3,r4,lr}
bx lr @ return
/******************************************************************/
/* put the heap back in max-heap order */
/******************************************************************/
/* r0 contains the address of table */
/* r1 contains the first index */
/* r2 contains the last index */
siftDown:
push {r1-r7,lr} @ save registers
@ r1 = root = start
mov r3,r2 @ save last index
1:
lsl r4,r1,#1
add r4,#1
cmp r4,r3
bgt 100f
add r5,r4,#1
cmp r5,r3
bgt 2f
ldr r6,[r0,r4,lsl #2] @ compare elements on the table
ldr r7,[r0,r5,lsl #2]
cmp r6,r7
movlt r4,r5
2:
ldr r7,[r0,r4,lsl #2] @ compare elements on the table
ldr r6,[r0,r1,lsl #2] @ root
cmp r6,r7
bge 100f
mov r2,r4 @ and r1 is root
bl swapElement
mov r1,r4 @ root = child
b 1b
 
100:
pop {r1-r7,lr}
bx lr @ return
 
/******************************************************************/
/* Display table elements */
/******************************************************************/
/* r0 contains the address of table */
displayTable:
push {r0-r3,lr} @ save registers
mov r2,r0 @ table address
mov r3,#0
1: @ loop display table
ldr r0,[r2,r3,lsl #2]
ldr r1,iAdrsMessValeur @ display value
bl conversion10 @ call function
ldr r0,iAdrsMessResult
bl affichageMess @ display message
add r3,#1
cmp r3,#NBELEMENTS - 1
ble 1b
ldr r0,iAdrszCarriageReturn
bl affichageMess
100:
pop {r0-r3,lr}
bx lr
/******************************************************************/
/* display text with size calculation */
/******************************************************************/
/* r0 contains the address of the message */
affichageMess:
push {r0,r1,r2,r7,lr} @ save registres
mov r2,#0 @ counter length
1: @ loop length calculation
ldrb r1,[r0,r2] @ read octet start position + index
cmp r1,#0 @ if 0 its over
addne r2,r2,#1 @ else add 1 in the length
bne 1b @ and loop
@ so here r2 contains the length of the message
mov r1,r0 @ address message in r1
mov r0,#STDOUT @ code to write to the standard output Linux
mov r7, #WRITE @ code call system "write"
svc #0 @ call systeme
pop {r0,r1,r2,r7,lr} @ restaur des 2 registres */
bx lr @ return
/******************************************************************/
/* Converting a register to a decimal unsigned */
/******************************************************************/
/* r0 contains value and r1 address area */
/* r0 return size of result (no zero final in area) */
/* area size => 11 bytes */
.equ LGZONECAL, 10
conversion10:
push {r1-r4,lr} @ save registers
mov r3,r1
mov r2,#LGZONECAL
1: @ start loop
bl divisionpar10U @ unsigned r0 <- dividende. quotient ->r0 reste -> r1
add r1,#48 @ digit
strb r1,[r3,r2] @ store digit on area
cmp r0,#0 @ stop if quotient = 0
subne r2,#1 @ else previous position
bne 1b @ and loop
@ and move digit from left of area
mov r4,#0
2:
ldrb r1,[r3,r2]
strb r1,[r3,r4]
add r2,#1
add r4,#1
cmp r2,#LGZONECAL
ble 2b
@ and move spaces in end on area
mov r0,r4 @ result length
mov r1,#' ' @ space
3:
strb r1,[r3,r4] @ store space in area
add r4,#1 @ next position
cmp r4,#LGZONECAL
ble 3b @ loop if r4 <= area size
100:
pop {r1-r4,lr} @ restaur registres
bx lr @return
/***************************************************/
/* division par 10 unsigned */
/***************************************************/
/* r0 dividende */
/* r0 quotient */
/* r1 remainder */
divisionpar10U:
push {r2,r3,r4, lr}
mov r4,r0 @ save value
//mov r3,#0xCCCD @ r3 <- magic_number lower raspberry 3
//movt r3,#0xCCCC @ r3 <- magic_number higter raspberry 3
ldr r3,iMagicNumber @ r3 <- magic_number raspberry 1 2
umull r1, r2, r3, r0 @ r1<- Lower32Bits(r1*r0) r2<- Upper32Bits(r1*r0)
mov r0, r2, LSR #3 @ r2 <- r2 >> shift 3
add r2,r0,r0, lsl #2 @ r2 <- r0 * 5
sub r1,r4,r2, lsl #1 @ r1 <- r4 - (r2 * 2) = r4 - (r0 * 10)
pop {r2,r3,r4,lr}
bx lr @ leave function
iMagicNumber: .int 0xCCCCCCCD
 
</syntaxhighlight>
 
=={{header|Arturo}}==
 
<syntaxhighlight lang="rebol">siftDown: function [items, start, ending][
root: start
a: new items
while [ending > 1 + 2 * root][
child: 1 + 2 * root
if and? ending > child + 1
a\[child+1] > a\[child] -> child: child + 1
 
if? a\[root] < a\[child][
tmp: a\[child]
a\[child]: a\[root]
a\[root]: tmp
root: child
]
else -> return a
]
return a
]
 
heapSort: function [items][
b: new items
count: size b
loop ((count-2)/2) .. 0 'start -> b: siftDown b start count
loop (count-1) .. 1 'ending [
tmp: b\[ending]
b\[ending]: b\0
b\0: tmp
b: siftDown b 0 ending
]
return b
]
 
print heapSort [3 1 2 8 5 7 9 4 6]</syntaxhighlight>
 
{{out}}
 
<pre>1 2 3 4 5 6 7 8 9</pre>
 
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">heapSort(a) {
Local end
end := %a%0
Line 257 ⟶ 1,354:
heapSort("a")
ListVars
MsgBox</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight lang="bbcbasic"> DIM test(9)
test() = 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
PROCheapsort(test())
Line 294 ⟶ 1,391:
IF a(r%) < a(c%) SWAP a(r%), a(c%) : r% = c% ELSE ENDPROC
ENDWHILE
ENDPROC</langsyntaxhighlight>
{{out}}
<pre>
Line 301 ⟶ 1,398:
 
=={{header|BCPL}}==
<langsyntaxhighlight BCPLlang="bcpl">// This can be run using Cintcode BCPL freely available from www.cl.cam.ac.uk/users/mr10.
 
GET "libhdr.h"
Line 342 ⟶ 1,439:
}
newline()
}</langsyntaxhighlight>
 
=={{header|C}}==
<langsyntaxhighlight lang="c">#include <stdio.h>
#include <stdlib.h>
 
int max (int *a, int n, int i, int j, int k) {
#define ValType double
int m = i;
#define IS_LESS(v1, v2) (v1 < v2)
if (j < n && a[j] > a[m]) {
m = j;
}
if (k < n && a[k] > a[m]) {
m = k;
}
return m;
}
 
void siftDowndownheap ( ValTypeint *a, int startn, int counti); {
while (1) {
int j = max(a, n, i, 2 * i + 1, 2 * i + 2);
if (j == i) {
break;
}
int t = a[i];
a[i] = a[j];
a[j] = t;
i = j;
}
}
 
void heapsort (int *a, int n) {
#define SWAP(r,s) do{ValType t=r; r=s; s=t; } while(0)
int i;
for (i = (n - 2) / 2; i >= 0; i--) {
downheap(a, n, i);
}
for (i = 0; i < n; i++) {
int t = a[n - i - 1];
a[n - i - 1] = a[0];
a[0] = t;
downheap(a, n - i - 1, 0);
}
}
 
int main () {
void heapsort( ValType *a, int count)
int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
{
int start,n end= sizeof a / sizeof a[0];
int i;
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
heapsort(a, n);
for (i = 0; i < n; i++)
printf("%d%s", a[i], i == n - 1 ? "\n" : " ");
return 0;
}
</syntaxhighlight>
 
=={{header|C sharp|C#}}==
/* heapify */
<syntaxhighlight lang="csharp">using System;
for (start = (count-2)/2; start >=0; start--) {
using System.Collections.Generic;
siftDown( a, start, count);
using System.Text;
 
public class HeapSortClass
{
public static void HeapSort<T>(T[] array)
{
HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);
}
 
public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)
for (end=count-1; end > 0; end--) {
{
SWAP(a[end],a[0]);
siftDownHeapSort<T>(aarray, 0offset, endlength, comparer.Compare);
}
}
 
public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)
void siftDown( ValType *a, int start, int end)
{
{
// build binary heap from all items
int root = start;
for (int i = 0; i < length; i++)
{
int index = i;
T item = array[offset + i]; // use next item
 
// and move it on top, if greater than parent
while ( root*2+1 < end ) {
int child = 2*root +while 1;(index > 0 &&
if ((child + 1 < end) && IS_LESS comparison(aarray[child],a[childoffset + (index - 1) / 2]), item) {< 0)
child += 1;{
int top = (index - 1) / 2;
array[offset + index] = array[offset + top];
index = top;
}
array[offset + index] = item;
}
 
if (IS_LESS(a[root], a[child])) {
for (int i = SWAP(length a[child],- a[root]1; )i > 0; i--)
root = child;{
// delete max and place it as last
T last = array[offset + i];
array[offset + i] = array[offset];
 
int index = 0;
// the last one positioned in the heap
while (index * 2 + 1 < i)
{
int left = index * 2 + 1, right = left + 1;
 
if (right < i && comparison(array[offset + left], array[offset + right]) < 0)
{
if (comparison(last, array[offset + right]) > 0) break;
 
array[offset + index] = array[offset + right];
index = right;
}
else
{
if (comparison(last, array[offset + left]) > 0) break;
 
array[offset + index] = array[offset + left];
index = left;
}
}
array[offset + index] = last;
}
else
return;
}
}
 
static void Main()
{
// usage
byte[] r = {5, 4, 1, 2};
HeapSort(r);
 
string[] s = { "-", "D", "a", "33" };
int main()
HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);
{
int ix;}
}</syntaxhighlight>
double valsToSort[] = {
1.4, 50.2, 5.11, -1.55, 301.521, 0.3301, 40.17,
-18.0, 88.1, 30.44, -37.2, 3012.0, 49.2};
#define VSIZE (sizeof(valsToSort)/sizeof(valsToSort[0]))
 
heapsort(valsToSort, VSIZE);
printf("{");
for (ix=0; ix<VSIZE; ix++) printf(" %.3f ", valsToSort[ix]);
printf("}\n");
return 0;
}</lang>
 
=={{header|C++}}==
Uses C++11. Compile with
g++ -std=c++11 heap.cpp
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iterator>
#include <iostream>
Line 422 ⟶ 1,590:
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}</langsyntaxhighlight>
{{out}}
<pre>
Line 431 ⟶ 1,599:
Uses C++11. Compile with
g++ -std=c++11
<langsyntaxhighlight lang="cpp">
#include <iostream>
#include <vector>
Line 478 ⟶ 1,646:
heap_sort(data);
for(int i : data) cout << i << " ";
}</langsyntaxhighlight>
{{out}}
<pre>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
</pre>
 
=={{header|C sharp|C#}}==
<lang csharp>using System;
using System.Collections.Generic;
using System.Text;
 
public class HeapSortClass
{
public static void HeapSort<T>(T[] array)
{
HeapSort<T>(array, 0, array.Length, Comparer<T>.Default);
}
 
public static void HeapSort<T>(T[] array, int offset, int length, IComparer<T> comparer)
{
HeapSort<T>(array, offset, length, comparer.Compare);
}
 
public static void HeapSort<T>(T[] array, int offset, int length, Comparison<T> comparison)
{
// build binary heap from all items
for (int i = 0; i < length; i++)
{
int index = i;
T item = array[offset + i]; // use next item
 
// and move it on top, if greater than parent
while (index > 0 &&
comparison(array[offset + (index - 1) / 2], item) < 0)
{
int top = (index - 1) / 2;
array[offset + index] = array[offset + top];
index = top;
}
array[offset + index] = item;
}
 
for (int i = length - 1; i > 0; i--)
{
// delete max and place it as last
T last = array[offset + i];
array[offset + i] = array[offset];
 
int index = 0;
// the last one positioned in the heap
while (index * 2 + 1 < i)
{
int left = index * 2 + 1, right = left + 1;
 
if (right < i && comparison(array[offset + left], array[offset + right]) < 0)
{
if (comparison(last, array[offset + right]) > 0) break;
 
array[offset + index] = array[offset + right];
index = right;
}
else
{
if (comparison(last, array[offset + left]) > 0) break;
 
array[offset + index] = array[offset + left];
index = left;
}
}
array[offset + index] = last;
}
}
 
static void Main()
{
// usage
byte[] r = {5, 4, 1, 2};
HeapSort(r);
 
string[] s = { "-", "D", "a", "33" };
HeapSort(s, 0, s.Length, StringComparer.CurrentCultureIgnoreCase);
}
}</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(defn- swap [a i j]
(assoc a i (nth a j) j (nth a i)))
Line 590 ⟶ 1,680:
([a]
(heap-sort a <)))
</syntaxhighlight>
</lang>
Example usage:
<langsyntaxhighlight lang="lisp">user> (heapsort [1 2 4 6 2 3 6])
[1 2 2 3 4 6 6]
user> (heapsort [1 2 4 6 2 3 6] >)
[6 6 4 3 2 2 1]
user> (heapsort (list 1 2 4 6 2 3 6))
[1 2 2 3 4 6 6]</langsyntaxhighlight>
 
=={{header|CLU}}==
<syntaxhighlight lang="clu">% Sort an array in place using heap-sort. The contained type
% may be any type that can be compared.
heapsort = cluster [T: type] is sort
where T has lt: proctype (T,T) returns (bool)
rep = null
aT = array[T]
sort = proc (a: aT)
% CLU arrays may start at any index.
% For simplicity, we will store the old index,
% reindex the array at zero, do the heap-sort,
% then undo the reindexing.
% This should be a constant-time operation.
old_low: int := aT$low(a)
aT$set_low(a, 0)
heapsort_(a)
aT$set_low(a, old_low)
end sort
% Heap-sort a zero-indexed array
heapsort_ = proc (a: aT)
heapify(a)
end_: int := aT$high(a)
while end_ > 0 do
swap(a, end_, 0)
end_ := end_ - 1
siftDown(a, 0, end_)
end
end heapsort_
heapify = proc (a: aT)
start: int := (aT$high(a) - 1) / 2
while start >= 0 do
siftDown(a, start, aT$high(a))
start := start - 1
end
end heapify
siftDown = proc (a: aT, start, end_: int)
root: int := start
while root*2 + 1 <= end_ do
child: int := root * 2 + 1
if child + 1 <= end_ cand a[child] < a[child + 1] then
child := child + 1
end
if a[root] < a[child] then
swap(a, root, child)
root := child
else
break
end
end
end siftDown
swap = proc (a: aT, i, j: int)
temp: T := a[i]
a[i] := a[j]
a[j] := temp
end swap
end heapsort
 
% Print an array
print_arr = proc [T: type] (s: stream, a: array[T], w: int)
where T has unparse: proctype (T) returns (string)
for e: T in array[T]$elements(a) do
stream$putright(s, T$unparse(e), w)
end
stream$putl(s, "")
end print_arr
 
% Test the heapsort
start_up = proc ()
po: stream := stream$primary_output()
arr: array[int] := array[int]$[9, -5, 3, 3, 24, -16, 3, -120, 250, 17]
stream$puts(po, "Before sorting: ")
print_arr[int](po,arr,5)
heapsort[int]$sort(arr)
stream$puts(po, "After sorting: ")
print_arr[int](po,arr,5)
end start_up</syntaxhighlight>
{{out}}
<pre>Before sorting: 9 -5 3 3 24 -16 3 -120 250 17
After sorting: -120 -16 -5 3 3 3 9 17 24 250</pre>
 
=={{header|COBOL}}==
{{works with|GnuCOBOL}}
<syntaxhighlight lang="cobol"> >>SOURCE FORMAT FREE
*> This code is dedicated to the public domain
*> This is GNUCOBOL 2.0
identification division.
program-id. heapsort.
environment division.
configuration section.
repository. function all intrinsic.
data division.
working-storage section.
01 filler.
03 a pic 99.
03 a-start pic 99.
03 a-end pic 99.
03 a-parent pic 99.
03 a-child pic 99.
03 a-sibling pic 99.
03 a-lim pic 99 value 10.
03 array-swap pic 99.
03 array occurs 10 pic 99.
procedure division.
start-heapsort.
 
*> fill the array
compute a = random(seconds-past-midnight)
perform varying a from 1 by 1 until a > a-lim
compute array(a) = random() * 100
end-perform
 
perform display-array
display space 'initial array'
 
*>heapify the array
move a-lim to a-end
compute a-start = (a-lim + 1) / 2
perform sift-down varying a-start from a-start by -1 until a-start = 0
 
perform display-array
display space 'heapified'
 
*> sort the array
move 1 to a-start
move a-lim to a-end
perform until a-end = a-start
move array(a-end) to array-swap
move array(a-start) to array(a-end)
move array-swap to array(a-start)
subtract 1 from a-end
perform sift-down
end-perform
 
perform display-array
display space 'sorted'
 
stop run
.
sift-down.
move a-start to a-parent
perform until a-parent * 2 > a-end
compute a-child = a-parent * 2
compute a-sibling = a-child + 1
if a-sibling <= a-end and array(a-child) < array(a-sibling)
*> take the greater of the two
move a-sibling to a-child
end-if
if a-child <= a-end and array(a-parent) < array(a-child)
*> the child is greater than the parent
move array(a-child) to array-swap
move array(a-parent) to array(a-child)
move array-swap to array(a-parent)
end-if
*> continue down the tree
move a-child to a-parent
end-perform
.
display-array.
perform varying a from 1 by 1 until a > a-lim
display space array(a) with no advancing
end-perform
.
end program heapsort.</syntaxhighlight>
{{out}}
<pre>prompt$ cobc -xj heapsort.cob
20 26 47 88 97 39 07 77 35 98 initial array
98 97 47 88 26 39 07 77 35 20 heapified
07 20 26 35 39 47 77 88 97 98 sorted</pre>
 
=={{header|CoffeeScript}}==
<langsyntaxhighlight lang="coffeescript"># Do an in-place heap sort.
heap_sort = (arr) ->
put_array_in_heap_order(arr)
Line 632 ⟶ 1,898:
arr = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8]
heap_sort arr
console.log arr</langsyntaxhighlight>
{{out}}
<pre>
Line 640 ⟶ 1,906:
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun make-heap (&optional (length 7))
(make-array length :adjustable t :fill-pointer 0))
 
Line 712 ⟶ 1,978:
(let ((h (make-heap (length sequence))))
(map nil #'(lambda (e) (heap-insert h e predicate)) sequence)
(map-into sequence #'(lambda () (heap-delete-min h predicate)))))</langsyntaxhighlight>
Example usage:
<pre>(heapsort (vector 1 9 2 8 3 7 4 6 5) '<) ; #(1 2 3 4 5 6 7 8 9)
Line 718 ⟶ 1,984:
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.container;
 
void heapSort(T)(T[] data) /*pure nothrow @safe @nogc*/ {
Line 728 ⟶ 1,994:
items.heapSort;
items.writeln;
}</langsyntaxhighlight>
 
A lower level implementation:
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
void heapSort(R)(R seq) pure nothrow @safe @nogc {
Line 762 ⟶ 2,028:
data.heapSort;
data.writeln;
}</langsyntaxhighlight>
 
=={{header|Dart}}==
<langsyntaxhighlight lang="dart">
void heapSort(List a) {
int count = a.length;
Line 836 ⟶ 2,102:
}
 
</syntaxhighlight>
</lang>
=={{header|Delphi}}==
See [https://rosettacode.org/wiki/Sorting_algorithms/Heapsort#Pascal Pascal].
 
=={{header|Draco}}==
<syntaxhighlight lang="draco">proc nonrec siftDown([*] int a; word start, end) void:
word root, child;
int temp;
bool stop;
root := start;
stop := false;
while not stop and root*2 + 1 <= end do
child := root*2 + 1;
if child+1 <= end and a[child] < a[child + 1] then
child := child + 1
fi;
if a[root] < a[child] then
temp := a[root];
a[root] := a[child];
a[child] := temp;
root := child
else
stop := true
fi
od
corp
 
proc nonrec heapify([*] int a; word count) void:
word start;
bool stop;
start := (count - 2) / 2;
stop := false;
while not stop do
siftDown(a, start, count-1);
if start=0
then stop := true /* avoid having to use a signed index */
else start := start - 1
fi
od
corp
 
proc nonrec heapsort([*] int a) void:
word end;
int temp;
heapify(a, dim(a,1));
end := dim(a,1) - 1;
while end > 0 do
temp := a[0];
a[0] := a[end];
a[end] := temp;
end := end - 1;
siftDown(a, 0, end)
od
corp
 
/* Test */
proc nonrec main() void:
int i;
[10] int a = (9, -5, 3, 3, 24, -16, 3, -120, 250, 17);
write("Before sorting: ");
for i from 0 upto 9 do write(a[i]:5) od;
writeln();
heapsort(a);
write("After sorting: ");
for i from 0 upto 9 do write(a[i]:5) od
corp</syntaxhighlight>
{{out}}
<pre>Before sorting: 9 -5 3 3 24 -16 3 -120 250 17
After sorting: -120 -16 -5 3 3 3 9 17 24 250</pre>
 
=={{header|E}}==
{{trans|Python}}
<langsyntaxhighlight lang="e">def heapsort := {
def cswap(c, a, b) {
def t := c[a]
Line 875 ⟶ 2,215:
}
}
}</langsyntaxhighlight>
 
=={{header|EasyLang}}==
 
<syntaxhighlight lang="text">
proc sort . d[] .
n = len d[]
# make heap
for i = 2 to n
if d[i] > d[(i + 1) div 2]
j = i
repeat
h = (j + 1) div 2
until d[j] <= d[h]
swap d[j] d[h]
j = h
.
.
.
for i = n downto 2
swap d[1] d[i]
j = 1
ind = 2
while ind < i
if ind + 1 < i and d[ind + 1] > d[ind]
ind += 1
.
if d[j] < d[ind]
swap d[j] d[ind]
.
j = ind
ind = 2 * j
.
.
.
data[] = [ 29 4 72 44 55 26 27 77 92 5 ]
sort data[]
print data[]
</syntaxhighlight>
 
=={{header|EchoLisp}}==
We use the heap library and the '''heap-pop''' primitive to implement heap-sort.
<syntaxhighlight lang="scheme">
(lib 'heap)
 
(define (heap-sort list)
(define heap (make-heap < )) ;; make a min heap
(list->heap list heap)
(while (not (heap-empty? heap))
(push 'stack (heap-pop heap)))
(stack->list 'stack))
 
(define L (shuffle (iota 15)))
→ (9 4 0 12 8 3 10 7 11 2 5 6 14 13 1)
(heap-sort L)
→ (0 1 2 3 4 5 6 7 8 9 10 11 12 13 14)
 
</syntaxhighlight>
 
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
HEAPSORT
Line 937 ⟶ 2,335:
sorted: is_sorted(ar)
end
 
feature{NONE}
 
is_sorted (ar: ARRAY [INTEGER]): BOOLEAN
--- Is 'ar' sorted in ascending order?
require
ar_not_empty: ar.is_empty = False
local
i: INTEGER
Line 949 ⟶ 2,347:
i := ar.lower
until
i >= ar.upper
loop
if ar [i] > ar [i + 1] then
Line 959 ⟶ 2,357:
 
end
</syntaxhighlight>
</lang>
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 996 ⟶ 2,394:
 
end
</syntaxhighlight>
</lang>
{{out}}
<pre>
Unsorted: 5 91 13 99 7 35
Sorted: 5 7 13 35 91 99
</pre>
 
=={{header|Elixir}}==
<syntaxhighlight lang="elixir">defmodule Sort do
def heapSort(list) do
len = length(list)
heapify(List.to_tuple(list), div(len - 2, 2))
|> heapSort(len-1)
|> Tuple.to_list
end
defp heapSort(a, finish) when finish > 0 do
swap(a, 0, finish)
|> siftDown(0, finish-1)
|> heapSort(finish-1)
end
defp heapSort(a, _), do: a
defp heapify(a, start) when start >= 0 do
siftDown(a, start, tuple_size(a)-1)
|> heapify(start-1)
end
defp heapify(a, _), do: a
defp siftDown(a, root, finish) when root * 2 + 1 <= finish do
child = root * 2 + 1
if child + 1 <= finish and elem(a,child) < elem(a,child + 1), do: child = child + 1
if elem(a,root) < elem(a,child),
do: swap(a, root, child) |> siftDown(child, finish),
else: a
end
defp siftDown(a, _root, _finish), do: a
defp swap(a, i, j) do
{vi, vj} = {elem(a,i), elem(a,j)}
a |> put_elem(i, vj) |> put_elem(j, vi)
end
end
 
(for _ <- 1..20, do: :rand.uniform(20)) |> IO.inspect |> Sort.heapSort |> IO.inspect</syntaxhighlight>
 
{{out}}
<pre>
[6, 1, 12, 3, 7, 7, 9, 20, 8, 15, 2, 10, 14, 5, 19, 7, 20, 9, 14, 19]
[1, 2, 3, 5, 6, 7, 7, 7, 8, 9, 9, 10, 12, 14, 14, 15, 19, 19, 20, 20]
</pre>
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let inline swap (a: _ []) i j =
let temp = a.[i]
a.[i] <- a.[j]
Line 1,025 ⟶ 2,468:
for term = n - 1 downto 1 do
swap a term 0
sift cmp a 0 term</langsyntaxhighlight>
 
=={{header|Forth}}==
This program assumes that return addresses simply reside as a single cell on the Return Stack. Most Forth compilers fulfill this requirement.
<langsyntaxhighlight lang="forth">create example
70 , 61 , 63 , 37 , 63 , 25 , 46 , 92 , 38 , 87 ,
 
Line 1,079 ⟶ 2,522:
: .array 10 0 do example i cells + ? loop cr ;
 
.array example 10 heapsort .array </langsyntaxhighlight>
 
 
<langsyntaxhighlight lang="forth">
\ Written in ANS-Forth; tested under VFX.
\ Requires the novice package: http://www.forth.org/novice.html
Line 1,166 ⟶ 2,609:
 
10 test-sort
</syntaxhighlight>
</lang>
{{out}}
<pre style="height:8ex;overflow:scroll">
Line 1,176 ⟶ 2,619:
{{works with|Fortran|90 and later}}
Translation of the pseudocode
<langsyntaxhighlight lang="fortran">program Heapsort_Demo
implicit none
Line 1,240 ⟶ 2,683:
end subroutine siftdown
 
end program Heapsort_Demo</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
<syntaxhighlight lang="freebasic">' version 22-10-2016
' compile with: fbc -s console
' for boundary checks on array's compile with: fbc -s console -exx
 
' sort from lower bound to the higher bound
' array's can have subscript range from -2147483648 to +2147483647
 
Sub siftdown(hs() As Long, start As ULong, end_ As ULong)
Dim As ULong root = start
Dim As Long lb = LBound(hs)
 
While root * 2 + 1 <= end_
Dim As ULong child = root * 2 + 1
If (child + 1 <= end_) AndAlso (hs(lb + child) < hs(lb + child + 1)) Then
child = child + 1
End If
If hs(lb + root) < hs(lb + child) Then
Swap hs(lb + root), hs(lb + child)
root = child
Else
Return
End If
Wend
End Sub
 
Sub heapsort(hs() As Long)
Dim As Long lb = LBound(hs)
Dim As ULong count = UBound(hs) - lb + 1
Dim As Long start = (count - 2) \ 2
Dim As ULong end_ = count - 1
 
While start >= 0
siftdown(hs(), start, end_)
start = start - 1
Wend
 
While end_ > 0
Swap hs(lb + end_), hs(lb)
end_ = end_ - 1
siftdown(hs(), 0, end_)
Wend
End Sub
 
' ------=< MAIN >=------
 
Dim As Long array(-7 To 7)
Dim As Long i, lb = LBound(array), ub = UBound(array)
 
Randomize Timer
For i = lb To ub : array(i) = i : Next
For i = lb To ub
Swap array(i), array(Int(Rnd * (ub - lb + 1)) + lb)
Next
 
Print "Unsorted"
For i = lb To ub
Print Using " ###"; array(i);
Next : Print : Print
 
heapsort(array())
 
Print "After heapsort"
For i = lb To ub
Print Using " ###"; array(i);
Next : Print
 
' empty keyboard buffer
While Inkey <> "" : Wend
Print : Print "hit any key to end program"
Sleep
End</syntaxhighlight>
{{out}}
<pre>Unsorted
0 3 -6 2 1 -4 7 5 6 -3 4 -7 -1 -5 -2
 
After heapsort
-7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7</pre>
 
=={{header|FunL}}==
Direct translation of the pseudocode. The array object (using Scala's <code>ArraySeq</code> class) has built-in method <code>length</code>, so the <code>count</code> parameter is not needed.
 
<langsyntaxhighlight lang="funl">def heapSort( a ) =
heapify( a )
end = a.length() - 1
Line 1,274 ⟶ 2,796:
a = array( [7, 2, 6, 1, 9, 5, 0, 3, 8, 4] )
heapSort( a )
println( a )</langsyntaxhighlight>
 
{{out}}
Line 1,286 ⟶ 2,808:
 
Since we want to implement a generic algorithm, we accept an argument of type <code>sort.Interface</code>, and thus do not have access to the actual elements of the container we're sorting. We can only swap elements. This causes a problem for us when implementing the <code>Pop</code> method, as we can't actually return an element. The ingenious step is realizing that <code>heap.Pop()</code> must move the value to pop to the "end" of the heap area, because its interface only has access to a "Swap" function, and a "Pop" function that pops from the end. (It does not have the ability to pop a value at the beginning.) This is perfect because we precisely want to move the thing popped to the end and shrink the "heap area" by 1. Our "Pop" function returns nothing since we can't get the value, but don't actually need it. (We only need the swapping that it does for us.)
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,323 ⟶ 2,845:
heapSort(sort.IntSlice(a))
fmt.Println("after: ", a)
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,330 ⟶ 2,852:
</pre>
If you want to implement it manually:
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,367 ⟶ 2,889:
root = child
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Loose translation of the pseudocode:
<langsyntaxhighlight lang="groovy">def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] }
 
def checkSwap = { list, i, j = i+1 -> [(list[i] > list[j])].find{ it }.each { makeSwap(list, i, j) } }
Line 1,395 ⟶ 2,917:
}
list
}</langsyntaxhighlight>
 
This is a better to read version. It includes comments and much better to understand and read function headers and loops.
It also has better readable variable names and can therefore be better used for study purposes.
It contains the same functions, even if a function with a single variable assignment in it is not very useful.
 
<syntaxhighlight lang="groovy">
def makeSwap (list, element1, element2) {
//exchanges two elements in a list.
//print a dot for each swap.
print "."
list[[element2,element1]] = list[[element1,element2]]
}
 
def checkSwap (list, child, parent) {
//check if parent is smaller than child, then swap.
if (list[parent] < list[child]) makeSwap(list, child, parent)
}
 
def siftDown (list, start, end) {
//end represents the limit of how far down the heap to sift
//start is the head of the heap
def parent = start
while (parent*2 < end) { //While the root has at least one child
def child = parent*2 + 1 //root*2+1 points to the left child
//find the child with the higher value
//if the child has a sibling and the child's value is less than its sibling's..
if (child + 1 <= end && list[child] < list[child+1]) child++ //point to the other child
if (checkSwap(list, child, parent)) { //check if parent is smaller than child and swap
parent = child //make child to next parent
} else {
return //The rest of the heap is in order - return.
}
}
}
 
def heapify (list) {
// Create a heap out of a list
// run through all the heap parents and
// ensure that each parent is lager than the child for all parent/childs.
// (list.size() -2) / 2 = last parent in the heap.
for (start in ((list.size()-2).intdiv(2))..0 ) {
siftDown(list, start, list.size() - 1)
}
}
 
def heapSort (list) {
//heap sort any unsorted list
heapify(list) //ensure that the list is in a binary heap state
//Run the list backwards and
//for end = (size of list -1 ) to 0
for (end in (list.size()-1)..0 ) {
makeSwap(list, 0, end) //put the top of the heap to the end (largest element)
siftDown(list, 0, end-1) //ensure that the rest is a heap again
}
list
}</syntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">println (heapSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4]))
println (heapSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1]))</langsyntaxhighlight>
{{out}}
<pre>.......................................................................[4, 12, 14, 23, 24, 24, 31, 35, 38, 46, 51, 57, 57, 58, 76, 78, 89, 92, 95, 97, 99]
Line 1,404 ⟶ 2,983:
 
=={{header|Haskell}}==
 
<syntaxhighlight lang="haskell">data Tree a = Nil
| Node a (Tree a) (Tree a)
deriving Show
 
insert :: Ord a => a -> Tree a -> Tree a
insert x Nil = Node x Nil Nil
insert x (Node y leftBranch rightBranch)
| x < y = Node x (insert y rightBranch) leftBranch
| otherwise = Node y (insert x rightBranch) leftBranch
 
merge :: Ord a => Tree a -> Tree a -> Tree a
merge Nil t = t
merge t Nil = t
merge tx@(Node vx lx rx) ty@(Node vy ly ry)
| vx < vy = Node vx (merge lx rx) ty
| otherwise = Node vy tx (merge ly ry)
 
fromList :: Ord a => [a] -> Tree a
fromList = foldr insert Nil
 
toList :: Ord a => Tree a -> [a]
toList Nil = []
toList (Node x l r) = x : toList (merge l r)
 
heapSort :: Ord a => [a] -> [a]
heapSort = toList . fromList</syntaxhighlight>
 
e.g
 
<syntaxhighlight lang="haskell">ghci> heapSort [9,5,8,2,1,4,6,3,0,7]
[0,1,2,3,4,5,6,7,8,9]
</syntaxhighlight>
 
Using package [http://hackage.haskell.org/package/fgl fgl] from HackageDB
<langsyntaxhighlight lang="haskell">import Data.Graph.Inductive.Internal.Heap(
Heap(..),insert,findMin,deleteMin)
 
Line 1,418 ⟶ 3,031:
where (x,r) = (findMin h,deleteMin h)
 
heapsortheapSort :: Ord a => [a] -> [a]
heapsortheapSort = (map fst) . toList . build . map (\x->(x,x))</langsyntaxhighlight>
e.g.
<langsyntaxhighlight lang="haskell">*Main> heapsort [[6,9],[2,13],[6,8,14,9],[10,7],[5]]
[[2,13],[5],[6,8,14,9],[6,9],[10,7]]</langsyntaxhighlight>
 
=={{header|Haxe}}==
{{trans|D}}
<syntaxhighlight lang="haxe">class HeapSort {
@:generic
private static function siftDown<T>(arr: Array<T>, start:Int, end:Int) {
var root = start;
while (root * 2 + 1 <= end) {
var child = root * 2 + 1;
if (child + 1 <= end && Reflect.compare(arr[child], arr[child + 1]) < 0)
child++;
if (Reflect.compare(arr[root], arr[child]) < 0) {
var temp = arr[root];
arr[root] = arr[child];
arr[child] = temp;
root = child;
} else {
break;
}
}
}
 
@:generic
public static function sort<T>(arr:Array<T>) {
if (arr.length > 1)
{
var start = (arr.length - 2) >> 1;
while (start > 0) {
siftDown(arr, start - 1, arr.length - 1);
start--;
}
}
 
var end = arr.length - 1;
while (end > 0) {
var temp = arr[end];
arr[end] = arr[0];
arr[0] = temp;
siftDown(arr, 0, end - 1);
end--;
}
}
}
 
class Main {
static function main() {
var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0];
var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3,
3.5, 0.0, -4.1, -9.5];
var stringArray = ['We', 'hold', 'these', 'truths', 'to',
'be', 'self-evident', 'that', 'all',
'men', 'are', 'created', 'equal'];
Sys.println('Unsorted Integers: ' + integerArray);
HeapSort.sort(integerArray);
Sys.println('Sorted Integers: ' + integerArray);
Sys.println('Unsorted Floats: ' + floatArray);
HeapSort.sort(floatArray);
Sys.println('Sorted Floats: ' + floatArray);
Sys.println('Unsorted Strings: ' + stringArray);
HeapSort.sort(stringArray);
Sys.println('Sorted Strings: ' + stringArray);
}
}</syntaxhighlight>
{{out}}
<pre>
Unsorted Integers: [1,10,2,5,-1,5,-19,4,23,0]
Sorted Integers: [-19,-1,0,1,2,4,5,5,10,23]
Unsorted Floats: [1,-3.2,5.2,10.8,-5.7,7.3,3.5,0,-4.1,-9.5]
Sorted Floats: [-9.5,-5.7,-4.1,-3.2,0,1,3.5,5.2,7.3,10.8]
Unsorted Strings: [We,hold,these,truths,to,be,self-evident,that,all,men,are,created,equal]
Sorted Strings: [We,all,are,be,created,equal,hold,men,self-evident,that,these,to,truths]
</pre>
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main() #: demonstrate various ways to sort a list and string
demosort(heapsort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
Line 1,461 ⟶ 3,146:
}
return X
end</langsyntaxhighlight>
Algorithm notes:
* This is a fairly straight forward implementation of the pseudo-code with 'heapify' coded in-line.
Line 1,481 ⟶ 3,166:
{{eff note|J|/:~}}
'''Translation of the pseudocode'''
<langsyntaxhighlight lang="j">swap=: C.~ <
 
siftDown=: 4 : 0
Line 1,497 ⟶ 3,182:
z=. siftDown&.>/ (c,~each i.<.c%2),<y NB. heapify
> ([ siftDown swap~)&.>/ (0,each}.i.c),z
)</langsyntaxhighlight>
'''Examples'''
<langsyntaxhighlight lang="j"> heapSort 1 5 2 7 3 9 4 6 8 1
1 1 2 3 4 5 6 7 8 9
 
heapSort &. (a.&i.) 'aqwcdhkij'
acdhijkqw</langsyntaxhighlight>
 
=={{header|Janet}}==
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.
 
<syntaxhighlight lang="janet">
(defn swap [l a b]
(let [aval (get l a) bval (get l b)]
(put l a bval)
(put l b aval)))
 
(defn heap-sort [l]
(def len (length l))
# Invariant: heap[parent] <= heap[*children]
(def heap (array/new (+ len 1)))
(array/push heap nil)
(def ROOT 1)
 
# Returns the parent index of index, or nil if none
(defn parent [idx]
(assert (> idx 0))
(if (= idx 1) nil (math/trunc (/ idx 2))))
# Returns a tuple [a b] of the two child indices of idx
(defn children [idx]
(def a (* idx 2))
(def b (+ a 1))
(def l (length heap))
# NOTE: `if` implicitly returns nil on false
[(if (< a l) a) (if (< b l) b)])
(defn check-invariants [idx]
(def [a b] (children idx))
(def p (parent idx))
(assert (or (nil? a) (<= (get heap idx) (get heap a))))
(assert (or (nil? b) (<= (get heap idx) (get heap b))))
(assert (or (nil? p) (>= (get heap idx) (get heap p)))))
(defn swim [idx]
(def val (get heap idx))
(def parent-idx (parent idx))
(when (and (not (nil? parent-idx)) (< val (get heap parent-idx)))
(swap heap parent-idx idx)
(swim parent-idx)
)
(check-invariants idx))
 
(defn sink [idx]
(def [a b] (children idx))
(def target-val (get heap idx))
(def smaller-children @[])
(defn handle-child [idx]
(let [child-val (get heap idx)]
(if (and (not (nil? idx)) (< child-val target-val))
(array/push smaller-children idx))))
(handle-child a)
(handle-child b)
(assert (<= (length smaller-children) 2))
(def smallest-child (cond
(empty? smaller-children) nil
(= 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: The `else` for final branch of `cond` is implicit
(get smaller-children 1)
))
(unless (nil? smallest-child)
(swap heap smallest-child idx)
(sink smallest-child)
# Recheck invariants
(check-invariants idx)))
 
(defn insert [val]
(def idx (length heap))
(array/push heap val)
(swim idx))
 
(defn remove-smallest []
(assert (> (length heap) 1))
(def largest (get heap ROOT))
(def new-root (array/pop heap))
(when (> (length heap) 1)
(put heap ROOT new-root)
(sink ROOT))
(assert (not (nil? largest)))
largest)
 
(each item l (insert item))
 
(def res @[])
(while (> (length heap) 1)
(array/push res (remove-smallest)))
res)
 
# NOTE: Makes a copy of input array. Output is mutable
(print (heap-sort [7 12 3 9 -1 17 6]))</syntaxhighlight>
{{out}}
<pre>
@[-1 3 6 7 9 12 17]
</pre>
 
=={{header|Java}}==
Direct translation of the pseudocode.
<langsyntaxhighlight lang="java">public static void heapSort(int[] a){
int count = a.length;
 
Line 1,559 ⟶ 3,342:
return;
}
}</langsyntaxhighlight>
 
=={{header|Javascript}}==
<syntaxhighlight lang="javascript">
{{trans|CoffeeScript}}
function heapSort(arr) {
<lang Javascript>
heapify(arr)
function swap(data, i, j) {
var tmpend = data[i];arr.length - 1
data[i]while =(end data[j];> 0) {
[arr[end], arr[0]] = [arr[0], arr[end]]
data[j] = tmp;
end--
siftDown(arr, 0, end)
}
}
 
function heap_sortheapify(arr) {
start = Math.floor(arr.length/2) - 1
put_array_in_heap_order(arr);
 
end = arr.length - 1;
while (endstart >= 0) {
swapsiftDown(arr, 0start, endarr.length - 1);
start--
sift_element_down_heap(arr, 0, end);
end -= 1
}
}
 
function put_array_in_heap_ordersiftDown(arr, startPos, endPos) {
let rootPos = startPos
var i;
 
i = arr.length / 2 - 1;
while (rootPos * 2 + 1 <= endPos) {
i = Math.floor(i);
while (i > childPos = 0)rootPos * 2 + {1
if (childPos + 1 <= endPos && arr[childPos] < arr[childPos + 1]) {
sift_element_down_heap(arr, i, arr.length);
i -= 1; childPos++
}
if (arr[rootPos] < arr[childPos]) {
[arr[rootPos], arr[childPos]] = [arr[childPos], arr[rootPos]]
rootPos = childPos
} else {
return
}
}
}
test('rosettacode', () => {
arr = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8,]
heapSort(arr)
expect(arr).toStrictEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15])
})</syntaxhighlight>
{{out}}
<pre>
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
</pre>
 
=={{header|jq}}==
function sift_element_down_heap(heap, i, max) {
{{works with|jq}}
var i_big, c1, c2;
'''Works with gojq, the Go implementation of jq'''
while(i < max) {
 
i_big = i;
Since jq is a purely functional language, the putative benefits of the heapsort algorithm do not accrue here.
c1 = 2*i + 1;
<syntaxhighlight lang="jq">def swap($a; $i; $j):
c2 = c1 + 1;
$a
if (c1 < max && heap[c1] > heap[i_big])
| .[$i] as $t
i_big = c1;
| .[$i] = .[$j]
if (c2 < max && heap[c2] > heap[i_big])
| .[$j] = $t i_big = c2;
 
if (i_big == i) return;
def siftDown($a; $start; $iend):
swap(heap,i, i_big);
{ $a, root: $start }
i = i_big;
| until( .stop or (.root*2 + 1 > $iend);
.child = .root*2 + 1
| if .child + 1 <= $iend and .a[.child] < .a[.child+1]
then .child += 1
else .
end
| if .a[.root] < .a[.child]
then
.a = swap(.a; .root; .child)
| .root = .child
else .stop = true
end)
| .a ;
 
def heapify:
length as $count
| {a: ., start: ((($count - 2)/2)|floor)}
| until(.start < 0;
.a = siftDown(.a; .start; $count - 1)
| .start += -1 )
| .a ;
def heapSort:
{ a: heapify,
iend: (length - 1) }
| until( .iend <= 0;
.a = swap(.a; 0; .iend)
| .iend += -1
| .a = siftDown(.a; 0; .iend) )
| .a ;
[4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3]
|
"Before: \(.)",
"After : \(heapSort)\n"
</syntaxhighlight>
{{out}}
<pre>
Before: [4,65,2,-31,0,99,2,83,782,1]
After : [-31,0,1,2,2,4,65,83,99,782]
 
Before: [7,5,2,6,1,4,2,6,3]
After : [1,2,2,3,4,5,6,6,7]
</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">function swap(a, i, j)
a[i], a[j] = a[j], a[i]
end
function pd!(a, first, last)
while (c = 2 * first - 1) < last
if c < last && a[c] < a[c + 1]
c += 1
end
if a[first] < a[c]
swap(a, c, first)
first = c
else
break
end
end
end
function heapify!(a, n)
f = div(n, 2)
while f >= 1
pd!(a, f, n)
f -= 1
end
end
function heapsort!(a)
n = length(a)
heapify!(a, n)
l = n
while l > 1
swap(a, 1, l)
l -= 1
pd!(a, 1, l)
end
return a
end
 
using Random: shuffle
a = shuffle(collect(1:12))
println("Unsorted: $a")
println("Heap sorted: ", heapsort!(a))
</syntaxhighlight>{{output}}<pre>
Unsorted: [3, 12, 11, 4, 2, 7, 5, 8, 9, 1, 10, 6]
Heap sorted: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
</pre>
 
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1.0
 
fun heapSort(a: IntArray) {
heapify(a)
var end = a.size - 1
while (end > 0) {
val temp = a[end]
a[end] = a[0]
a[0] = temp
end--
siftDown(a, 0, end)
}
}
 
fun heapify(a: IntArray) {
arr = [12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8,];
var start = (a.size - 2) / 2
heap_sort(arr);
while (start >= 0) {
alert(arr);</lang>
siftDown(a, start, a.size - 1)
start--
}
}
 
fun siftDown(a: IntArray, start: Int, end: Int) {
var root = start
while (root * 2 + 1 <= end) {
var child = root * 2 + 1
if (child + 1 <= end && a[child] < a[child + 1]) child++
if (a[root] < a[child]) {
val temp = a[root]
a[root] = a[child]
a[child] = temp
root = child
}
else return
}
}
 
fun main(args: Array<String>) {
val aa = arrayOf(
intArrayOf(100, 2, 56, 200, -52, 3, 99, 33, 177, -199),
intArrayOf(4, 65, 2, -31, 0, 99, 2, 83, 782, 1),
intArrayOf(12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8)
)
for (a in aa) {
heapSort(a)
println(a.joinToString(", "))
}
}</syntaxhighlight>
 
{{out}}
<pre>
-199, [1-52, 2, 3, 4, 5, 6, 7, 8, 9, 1033, 1156, 1299, 13100, 14177, 15]200
-31, 0, 1, 2, 2, 4, 65, 83, 99, 782
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
</pre>
 
=={{header|Liberty BASIC}}==
<langsyntaxhighlight lang="lb">wikiSample=1 'comment out for random array
 
data 6, 5, 3, 1, 8, 7, 2, 4
Line 1,692 ⟶ 3,632:
next i
print
end sub</langsyntaxhighlight>
 
=={{header|Lobster}}==
<syntaxhighlight lang="lobster">def siftDown(a, start, end):
// (end represents the limit of how far down the heap to sift)
var root = start
 
while root * 2 + 1 <= end: // (While the root has at least one child)
var child = root * 2 + 1 // (root*2+1 points to the left child)
// (If the child has a sibling and the child's value is less than its sibling's...)
if child + 1 <= end and a[child] < a[child + 1]:
child += 1 // (... then point to the right child instead)
if a[root] < a[child]: // (out of max-heap order)
let r = a[root] // swap(a[root], a[child])
a[root] = a[child]
a[child] = r
root = child // (repeat to continue sifting down the child now)
else:
return
 
def heapify(a, count):
//(start is assigned the index in a of the last parent node)
var start = (count - 2) >> 1
 
while start >= 0:
// (sift down the node at index start to the proper place
// such that all nodes below the start index are in heap order)
siftDown(a, start, count-1)
start -= 1
// (after sifting down the root all nodes/elements are in heap order)
 
def heapSort(a):
// input: an unordered array a of length count
let count = a.length
// (first place a in max-heap order)
heapify(a, count)
 
var end = count - 1
while end > 0:
//(swap the root(maximum value) of the heap with the last element of the heap)
let z = a[0]
a[0] = a[end]
a[end] = z
//(decrement the size of the heap so that the previous max value will stay in its proper place)
end -= 1
// (put the heap back in max-heap order)
siftDown(a, 0, end)
 
let inputi = [1,10,2,5,-1,5,-19,4,23,0]
print ("input: " + inputi)
heapSort(inputi)
print ("sorted: " + inputi)
let inputf = [1,-3.2,5.2,10.8,-5.7,7.3,3.5,0,-4.1,-9.5]
print ("input: " + inputf)
heapSort(inputf)
print ("sorted: " + inputf)
let inputs = ["We","hold","these","truths","to","be","self-evident","that","all","men","are","created","equal"]
print ("input: " + inputs)
heapSort(inputs)
print ("sorted: " + inputs)
</syntaxhighlight>
{{out}}
<pre>
input: [1, 10, 2, 5, -1, 5, -19, 4, 23, 0]
sorted: [-19, -1, 0, 1, 2, 4, 5, 5, 10, 23]
input: [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0.0, -4.1, -9.5]
sorted: [-9.5, -5.7, -4.1, -3.2, 0.0, 1.0, 3.5, 5.2, 7.3, 10.8]
input: ["We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal"]
sorted: ["We", "all", "are", "be", "created", "equal", "hold", "men", "self-evident", "that", "these", "to", "truths"]
</pre>
 
=={{header|LotusScript}}==
 
<syntaxhighlight lang="lotusscript">
<lang LotusScript>
Public Sub heapsort(pavIn As Variant)
Dim liCount As Integer, liEnd As Integer
Line 1,743 ⟶ 3,751:
wend
End Sub
</syntaxhighlight>
 
 
 
 
</lang>
 
=={{header|M4}}==
<langsyntaxhighlight M4lang="m4">divert(-1)
 
define(`randSeed',141592653)
Line 1,805 ⟶ 3,809:
show(`a')
heapsort(`a')
show(`a')</langsyntaxhighlight>
 
=={{header|MathematicaMaple}}==
<syntaxhighlight lang="text">swap := proc(arr, a, b)
<lang Mathematica>siftDown[list_,root_,theEnd_]:=
local temp:
temp := arr[a]:
arr[a] := arr[b]:
arr[b] := temp:
end proc:
heapify := proc(toSort, n, i)
local largest, l, r, holder:
largest := i:
l := 2*i:
r := 2*i+1:
if (l <= n and toSort[l] > toSort[largest]) then
largest := l:
end if:
if (r <= n and toSort[r] > toSort[largest]) then
largest := r:
end if:
if (not largest = i) then
swap(toSort, i, largest);
heapify(toSort, n, largest):
end if:
end proc:
heapsort := proc(arr)
local n,i:
n := numelems(arr):
for i from trunc(n/2) to 1 by -1 do
heapify(arr, n, i):
end do:
for i from n to 2 by -1 do
swap(arr, 1, i):
heapify(arr, i-1, 1):
end do:
end proc:
arr := Array([17,3,72,0,36,2,3,8,40,0]);
heapsort(arr);
arr;</syntaxhighlight>
{{Out|Output}}
<pre>[0,0,2,3,3,8,17,36,40,72]</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<syntaxhighlight lang="mathematica">siftDown[list_,root_,theEnd_]:=
While[(root*2) <= theEnd,
child = root*2;
Line 1,817 ⟶ 3,861:
]
]
 
heapSort[list_] := Module[{ count, start},
count = Length[list]; start = Floor[count/2];
Line 1,826 ⟶ 3,869:
count--; list = siftDown[list,1,count];
]
]</langsyntaxhighlight>
{{out}}
<pre>heapSort@{2,3,1,5,7,6}
Line 1,833 ⟶ 3,876:
=={{header|MATLAB}} / {{header|Octave}}==
This function definition is an almost exact translation of the pseudo-code into MATLAB, but I have chosen to make the heapify function inline because it is only called once in the pseudo-code. Also, MATLAB uses 1 based array indecies, therefore all of the pseudo-code has been translated to reflect that difference.
<langsyntaxhighlight MATLABlang="matlab">function list = heapSort(list)
 
function list = siftDown(list,root,theEnd)
Line 1,872 ⟶ 3,915:
end
end</langsyntaxhighlight>
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> heapSort([4 3 1 5 6 2])
 
ans =
 
1 2 3 4 5 6</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight MAXScriptlang="maxscript">fn heapify arr count =
(
local s = count /2
Line 1,923 ⟶ 3,966:
)
)</langsyntaxhighlight>
Output:
<syntaxhighlight lang="maxscript">
<lang MAXScript>
a = for i in 1 to 10 collect random 0 9
#(7, 2, 5, 6, 1, 5, 4, 0, 1, 6)
heapSort a
#(0, 1, 1, 2, 4, 5, 5, 6, 6, 7)
</syntaxhighlight>
</lang>
 
=={{header|Mercury}}==
{{works with|Mercury|22.01.1}}
 
 
<syntaxhighlight lang="mercury">%%%-------------------------------------------------------------------
 
:- module heapsort_task.
 
:- interface.
:- import_module io.
:- pred main(io::di, io::uo) is det.
 
:- implementation.
:- import_module array.
:- import_module int.
:- import_module list.
:- import_module random.
:- import_module random.sfc16.
 
%%%-------------------------------------------------------------------
%%%
%%% heapsort/3 --
%%%
%%% A generic heapsort predicate. It takes a "Less_than" predicate to
%%% determine the order of the sort.
%%%
%%% That I call the predicate "Less_than" does not, by any means,
%%% preclude a descending order. This "Less_than" refers to the
%%% ordinals of the sequence. In other words, it means "comes before".
%%%
%%% The implementation closely follows the task pseudocode--although,
%%% of course, loops have been turned into tail recursions and arrays
%%% are treated as state variables.
%%%
 
:- pred heapsort(pred(T, T)::pred(in, in) is semidet,
array(T)::array_di, array(T)::array_uo) is det.
heapsort(Less_than, !Arr) :-
heapsort(Less_than, size(!.Arr), !Arr).
 
:- pred heapsort(pred(T, T)::pred(in, in) is semidet, int::in,
array(T)::array_di, array(T)::array_uo) is det.
heapsort(Less_than, Count, !Arr) :-
heapify(Less_than, Count, !Arr),
heapsort_loop(Less_than, Count, Count - 1, !Arr).
 
:- pred heapsort_loop(pred(T, T)::pred(in, in) is semidet,
int::in, int::in,
array(T)::array_di, array(T)::array_uo) is det.
heapsort_loop(Less_than, Count, End, !Arr) :-
if (End = 0) then true
else (swap(End, 0, !Arr),
sift_down(Less_than, 0, End - 1, !Arr),
heapsort_loop(Less_than, Count, End - 1, !Arr)).
 
:- pred heapify(pred(T, T)::pred(in, in) is semidet, int::in,
array(T)::array_di, array(T)::array_uo) is det.
heapify(Less_than, Count, !Arr) :-
heapify(Less_than, Count, (Count - 2) // 2, !Arr).
 
:- pred heapify(pred(T, T)::pred(in, in) is semidet,
int::in, int::in,
array(T)::array_di, array(T)::array_uo) is det.
heapify(Less_than, Count, Start, !Arr) :-
if (Start = -1) then true
else (sift_down(Less_than, Start, Count - 1, !Arr),
heapify(Less_than, Count, Start - 1, !Arr)).
 
:- pred sift_down(pred(T, T)::pred(in, in) is semidet,
int::in, int::in,
array(T)::array_di, array(T)::array_uo) is det.
sift_down(Less_than, Root, End, !Arr) :-
if (End < (Root * 2) + 1) then true
else (locate_child(Less_than, Root, End, !.Arr, Child),
(if not Less_than(!.Arr^elem(Root), !.Arr^elem(Child))
then true
else (swap(Root, Child, !Arr),
sift_down(Less_than, Child, End, !Arr)))).
 
:- pred locate_child(pred(T, T)::pred(in, in) is semidet,
int::in, int::in,
array(T)::in, int::out) is det.
locate_child(Less_than, Root, End, Arr, Child) :-
Child0 = (Root * 2) + 1,
(if (End =< Child0 + 1)
then (Child = Child0)
else if not Less_than(Arr^elem(Child0), Arr^elem(Child0 + 1))
then (Child = Child0)
else (Child = Child0 + 1)).
 
%%%-------------------------------------------------------------------
 
main(!IO) :-
R = (sfc16.init),
make_io_random(R, M, !IO),
Generate = (pred(Index::in, Number::out, IO1::di, IO::uo) is det :-
uniform_int_in_range(M, min(0, Index), 10, Number,
IO1, IO)),
generate_foldl(30, Generate, Arr0, !IO),
print_line(Arr0, !IO),
heapsort(<, Arr0, Arr1),
print_line(Arr1, !IO),
heapsort(>=, Arr1, Arr2),
print_line(Arr2, !IO).
 
%%%-------------------------------------------------------------------
%%% local variables:
%%% mode: mercury
%%% prolog-indent-width: 2
%%% end:</syntaxhighlight>
 
{{out}}
<pre>$ mmc heapsort_task.m && ./heapsort_task
array([3, 9, 3, 8, 5, 7, 0, 7, 3, 9, 5, 0, 1, 2, 0, 5, 8, 0, 8, 3, 8, 2, 6, 6, 8, 5, 7, 6, 5, 7])
array([0, 0, 0, 0, 1, 2, 2, 3, 3, 3, 3, 5, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9])
array([9, 9, 8, 8, 8, 8, 8, 7, 7, 7, 7, 6, 6, 6, 5, 5, 5, 5, 5, 3, 3, 3, 3, 2, 2, 1, 0, 0, 0, 0])</pre>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
 
Line 2,015 ⟶ 4,175:
end root
 
return a</langsyntaxhighlight>
{{out}}
<pre>
Line 2,038 ⟶ 4,198:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc siftDown[T](a: var openarray[T]; start, ending: int) =
var root = start
while root * 2 + 1 < ending:
Line 2,060 ⟶ 4,220:
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
heapSort a
echo a</langsyntaxhighlight>
{{out}}
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
Line 2,066 ⟶ 4,226:
=={{header|Objeck}}==
{{trans|Java}}
<langsyntaxhighlight lang="objeck">bundle Default {
class HeapSort {
function : Main(args : String[]) ~ Nil {
Line 2,118 ⟶ 4,278:
}
}
}</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">let heapsort a =
 
let swap i j =
Line 2,143 ⟶ 4,303:
swap term 0;
sift 0 term;
done;;</langsyntaxhighlight>
Usage:
<langsyntaxhighlight lang="ocaml">let a = [|3;1;4;1;5;9;2;6;5;3;5;8;97;93;23;84;62;64;33;83;27;95|] in
heapsort a;
Array.iter (Printf.printf "%d ") a;;
Line 2,154 ⟶ 4,314:
heapsort b;
Array.iter print_char b;;
print_newline ();;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,163 ⟶ 4,323:
=={{header|Oz}}==
A faithful translation of the pseudocode, adjusted to the fact that Oz arrays can start with an arbitrary index, not just 0 or 1.
<langsyntaxhighlight lang="oz">declare
proc {HeapSort A}
Low = {Array.low A}
Line 2,219 ⟶ 4,379:
in
{HeapSort Arr}
{Show {Array.toRecord unit Arr}}</langsyntaxhighlight>
 
=={{header|Pascal}}==
{{works with|FPC}}
An example, which works on arrays with arbitrary bounds :-)
<syntaxhighlight lang ="pascal">program HeapSortDemo;
program HeapSortDemo;
 
{$mode objfpc}{$h+}{$b-}
type
TIntArray = array[4..15] of integer;
var
data: TIntArray;
i: integer;
procedure siftDown(var a: TIntArray; start, ende: integer);
var
root, child, swap: integer;
begin
root := start;
while root * 2 - start + 1 <= ende do
begin
child := root * 2 - start + 1;
if (child + 1 <= ende) and (a[child] < a[child + 1]) then
inc(child);
if a[root] < a[child] then
begin
swap := a[root];
a[root] := a[child];
a[child] := swap;
root := child;
end
else
exit;
end;
end;
 
procedure heapifyHeapSort(var a: TIntArrayarray of Integer);
procedure SiftDown(Root, Last: Integer);
var
startChild, countTmp: integerInteger;
begin
while Root * 2 + 1 <= Last do begin
count := length(a);
start Child := low(a)Root + count div* 2 -+ 1;
if (Child + 1 <= Last) and (a[Child] < a[Child + 1]) then
while start >= low(a) do
begin Inc(Child);
if a[Root] < a[Child] then begin
siftdown(a, start, high(a));
dec(start) Tmp := a[Root];
a[Root] := a[Child];
a[Child] := Tmp;
Root := Child;
end else exit;
end;
end;
var
 
I, Tmp: Integer;
procedure heapSort(var a: TIntArray);
begin
var
for I := Length(a) div 2 downto 0 do
ende, swap: integer;
SiftDown(I, High(a));
begin
for I := High(a) downto 1 do begin
heapify(a);
endeTmp := high(a)[0];
whilea[0] ende:= > low(a) do[I];
begina[I] := Tmp;
SiftDown(0, I swap- := a[low(a1)];
a[low(a)] := a[ende];
a[ende] := swap;
dec(ende);
siftdown(a, low(a), ende);
end;
end;
end;
 
procedure PrintArray(const Name: string; const A: array of Integer);
var
I: Integer;
begin
Write(Name, ': [');
Randomize;
for I := 0 to High(A) - 1 do
writeln('The data before sorting:');
for i := lowWrite(data)A[I], to', high(data') do;
WriteLn(A[High(A)], ']');
begin
end;
data[i] := Random(high(data));
 
write(data[i]:4);
var
end;
a1: array[-7..5] of Integer = (-34, -20, 30, 13, 36, -10, 5, -25, 9, 19, 35, -50, 29);
writeln;
a2: array of Integer = (-9, 42, -38, -5, -38, 0, 0, -15, 37, 7, -7, 40);
heapSort(data);
begin
writeln('The data after sorting:');
HeapSort(a1);
for i := low(data) to high(data) do
PrintArray('a1', a1);
begin
writeHeapSort(data[i]:4a2);
PrintArray('a2', a2);
end;
end.
writeln;
</syntaxhighlight>
end.</lang>
{{out}}
<pre>
a1: [-50, -34, -25, -20, -10, 5, 9, 13, 19, 29, 30, 35, 36]
The data before sorting:
a2: [-38, -38, -15, -9, -7, -5, 0, 0, 7, 37, 40, 42]
12 13 0 1 0 14 13 10 1 10 9 2
The data after sorting:
0 0 1 1 2 9 10 10 12 13 13 14
</pre>
 
=={{header|Perl}}==
<syntaxhighlight lang="perl">#!/usr/bin/perl
Translation of the pseudocode.
<lang perl>my @my_list = (2,3,6,23,13,5,7,3,4,5);
heap_sort(\@my_list);
print "@my_list\n";
exit;
 
my @a = (4, 65, 2, -31, 0, 99, 2, 83, 782, 1);
sub heap_sort
print "@a\n";
{
heap_sort(\@a);
my($list) = @_;
print "@a\n";
my $count = scalar @$list;
heapify($count,$list);
 
sub heap_sort {
my $end = $count - 1;
my while($enda) >= 0)@_;
my $n = {@$a;
for (my $i = ($n - 2) / 2; @$list[0,$end]i >= @$list[$end,0]; $i--) {
sift_downdown_heap(0$a, $end-1n, $listi);
$end--;
}
}
sub heapify
{
my ($count,$list) = @_;
my $start = ($count - 2) / 2;
while($start >= 0)
{
sift_down($start,$count-1,$list);
$start--;
}
}
sub sift_down
{
my($start,$end,$list) = @_;
 
my $root = $start;
while($root * 2 + 1 <= $end)
{
my $child = $root * 2 + 1;
$child++ if($child + 1 <= $end && $list->[$child] < $list->[$child+1]);
if($list->[$root] < $list->[$child])
{
@$list[$root,$child] = @$list[$child,$root];
$root = $child;
}else{ return }
}
}</lang>
 
=={{header|Perl 6}}==
<lang perl6>sub heap_sort ( @list is rw ) {
for ( 0 ..^ +@list div 2 ).reverse -> $start {
_sift_down $start, @list.end, @list;
}
for (my $i = 0; $i < $n; $i++) {
 
for ( 1 ..^ +@listmy ).reverse$t = $a->[$n - $endi {- 1];
@list$a->[$n 0,- $endi - 1] .= reverse$a->[0];
_sift_down 0, $enda-1,>[0] @list= $t;
down_heap($a, $n - $i - 1, 0);
}
}
 
sub down_heap {
sub _sift_down ( $start, $end, @list is rw ) {
my ($roota, =$n, $starti) = @_;
while ( my $child = $root * 2 + 1 ) <= $end {
my $child++j if= max($childa, +$n, 1$i, <=2 * $endi and+ [<]1, @list[2 $child,* $childi +1 ]2);
returnlast if @list[$root]j >== @list[$child]i;
@list[my $root,t = $child a->[$i] .= reverse;
$roota->[$i] = $childa->[$j];
$a->[$j] = $t;
$i = $j;
}
}
 
sub max {
my @data = 6, 7, 2, 1, 8, 9, 5, 3, 4;
my ($a, $n, $i, $j, $k) = @_;
say 'Input = ' ~ @data;
my $m = $i;
@data.&heap_sort;
$m = $j if $j < $n && $a->[$j] > $a->[$m];
say 'Output = ' ~ @data;</lang>
$m = $k if $k < $n && $a->[$k] > $a->[$m];
return $m;
}
</syntaxhighlight>
 
=={{header|Phix}}==
<!--<syntaxhighlight lang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">siftDown</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">arr</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">last</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">root</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">s</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">root</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span><span style="color: #0000FF;"><=</span><span style="color: #000000;">last</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">child</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">root</span><span style="color: #0000FF;">*</span><span style="color: #000000;">2</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">child</span><span style="color: #0000FF;"><</span><span style="color: #000000;">last</span> <span style="color: #008080;">and</span> <span style="color: #000000;">arr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">child</span><span style="color: #0000FF;">]<</span><span style="color: #000000;">arr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">child</span><span style="color: #0000FF;">+</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span>
<span style="color: #000000;">child</span> <span style="color: #0000FF;">+=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #008080;">if</span> <span style="color: #000000;">arr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">root</span><span style="color: #0000FF;">]>=</span><span style="color: #000000;">arr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">child</span><span style="color: #0000FF;">]</span> <span style="color: #008080;">then</span> <span style="color: #008080;">exit</span> <span style="color: #008080;">end</span> <span style="color: #008080;">if</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">tmp</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">arr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">root</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">arr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">root</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">arr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">child</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">arr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">child</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tmp</span>
<span style="color: #000000;">root</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">child</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">arr</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">heapify</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">arr</span><span style="color: #0000FF;">,</span> <span style="color: #004080;">integer</span> <span style="color: #000000;">count</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">floor</span><span style="color: #0000FF;">(</span><span style="color: #000000;">count</span><span style="color: #0000FF;">/</span><span style="color: #000000;">2</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">s</span><span style="color: #0000FF;">></span><span style="color: #000000;">0</span> <span style="color: #008080;">do</span>
<span style="color: #000000;">arr</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">siftDown</span><span style="color: #0000FF;">(</span><span style="color: #000000;">arr</span><span style="color: #0000FF;">,</span><span style="color: #000000;">s</span><span style="color: #0000FF;">,</span><span style="color: #000000;">count</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">s</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">arr</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #008080;">function</span> <span style="color: #000000;">heap_sort</span><span style="color: #0000FF;">(</span><span style="color: #004080;">sequence</span> <span style="color: #000000;">arr</span><span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">last</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">length</span><span style="color: #0000FF;">(</span><span style="color: #000000;">arr</span><span style="color: #0000FF;">)</span>
<span style="color: #000000;">arr</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">heapify</span><span style="color: #0000FF;">(</span><span style="color: #000000;">arr</span><span style="color: #0000FF;">,</span><span style="color: #000000;">last</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">while</span> <span style="color: #000000;">last</span><span style="color: #0000FF;">></span><span style="color: #000000;">1</span> <span style="color: #008080;">do</span>
<span style="color: #004080;">object</span> <span style="color: #000000;">tmp</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">arr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">arr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">1</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">arr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">last</span><span style="color: #0000FF;">]</span>
<span style="color: #000000;">arr</span><span style="color: #0000FF;">[</span><span style="color: #000000;">last</span><span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">tmp</span>
<span style="color: #000000;">last</span> <span style="color: #0000FF;">-=</span> <span style="color: #000000;">1</span>
<span style="color: #000000;">arr</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">siftDown</span><span style="color: #0000FF;">(</span><span style="color: #000000;">arr</span><span style="color: #0000FF;">,</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #000000;">last</span><span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<span style="color: #008080;">return</span> <span style="color: #000000;">arr</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #0000FF;">?</span><span style="color: #000000;">heap_sort</span><span style="color: #0000FF;">({</span><span style="color: #000000;">5</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"oranges"</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"and"</span><span style="color: #0000FF;">,</span><span style="color: #000000;">3</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"apples"</span><span style="color: #0000FF;">})</span>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{3,5,"and","apples","oranges"}
Input = 6 7 2 1 8 9 5 3 4
Output = 1 2 3 4 5 6 7 8 9
</pre>
 
=={{header|Picat}}==
<syntaxhighlight lang="picat">main =>
_ = random2(),
A = [random(-10,10) : _ in 1..30],
println(A),
heapSort(A),
println(A).
 
heapSort(A) =>
heapify(A),
End = A.len,
while (End > 1)
swap(A, End, 1),
End := End - 1,
siftDown(A, 1, End)
end.
 
heapify(A) =>
Count = A.len,
Start = Count // 2,
while (Start >= 1)
siftDown(A, Start, Count),
Start := Start - 1
end.
siftDown(A, Start, End) =>
Root = Start,
Loop = true,
while (Root * 2 - 1 < End, Loop == true)
Child := Root * 2- 1,
if Child + 1 <= End, A[Child] @< A[Child+1] then
Child := Child + 1
end,
if A[Root] @< A[Child] then
swap(A,Root, Child),
Root := Child
else
Loop := false
end
end.
 
swap(L,I,J) =>
T = L[I],
L[I] := L[J],
L[J] := T.</syntaxhighlight>
 
{{out}}
<pre>[6,2,3,1,9,2,5,1,-7,1,2,1,-1,-7,2,0,4,-6,4,-8,1,9,3,5,-6,-6,0,7,-8,-2]
[-8,-8,-7,-7,-6,-6,-6,-2,-1,0,0,1,1,1,1,1,2,2,2,2,3,3,4,4,5,5,6,7,9,9]</pre>
 
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de heapSort (A Cnt)
(let Cnt (length A)
(for (Start (/ Cnt 2) (gt0 Start) (dec Start))
Line 2,407 ⟶ 4,607:
(NIL (> (get A Child) (get A Root)))
(xchg (nth A Root) (nth A Child))
(setq Root Child) ) ) )</langsyntaxhighlight>
{{out}}
<pre>: (heapSort (make (do 9 (link (rand 1 999)))))
Line 2,413 ⟶ 4,613:
 
=={{header|PL/I}}==
<langsyntaxhighlight lang="pli">*process source xref attributes or(!);
/*********************************************************************
* Pseudocode found here:
Line 2,488 ⟶ 4,688:
End;
 
End;</langsyntaxhighlight>
{{out}}
<pre>
Line 2,543 ⟶ 4,743:
element 24 after sort xi
element 25 after sort zeta
</pre>
 
=={{header|PL/M}}==
<syntaxhighlight lang="plm">100H:
 
/* HEAP SORT AN ARRAY OF 16-BIT INTEGERS */
HEAP$SORT: PROCEDURE (AP, COUNT);
SIFT$DOWN: PROCEDURE (AP, START, ENDV);
DECLARE (AP, A BASED AP) ADDRESS;
DECLARE (START, ENDV, ROOT, CHILD, TEMP) ADDRESS;
ROOT = START;
DO WHILE (CHILD := SHL(ROOT,1) + 1) <= ENDV;
IF CHILD + 1 <= ENDV AND A(CHILD) < A(CHILD+1) THEN
CHILD = CHILD + 1;
IF A(ROOT) < A(CHILD) THEN DO;
TEMP = A(ROOT);
A(ROOT) = A(CHILD);
A(CHILD) = TEMP;
ROOT = CHILD;
END;
ELSE RETURN;
END;
END SIFT$DOWN;
 
HEAPIFY: PROCEDURE (AP, COUNT);
DECLARE (AP, COUNT, START) ADDRESS;
START = (COUNT-2) / 2;
LOOP:
CALL SIFT$DOWN(AP, START, COUNT-1);
IF START = 0 THEN RETURN;
START = START - 1;
GO TO LOOP;
END HEAPIFY;
DECLARE (AP, COUNT, ENDV, TEMP, A BASED AP) ADDRESS;
CALL HEAPIFY(AP, COUNT);
ENDV = COUNT - 1;
DO WHILE ENDV > 0;
TEMP = A(0);
A(0) = A(ENDV);
A(ENDV) = TEMP;
ENDV = ENDV - 1;
CALL SIFT$DOWN(AP, 0, ENDV);
END;
END HEAP$SORT;
 
/* CP/M CALLS AND FUNCTION TO PRINT INTEGERS */
BDOS: PROCEDURE (FN, ARG);
DECLARE FN BYTE, ARG ADDRESS;
GO TO 5;
END BDOS;
 
PRINT$NUMBER: PROCEDURE (N);
DECLARE S (7) BYTE INITIAL ('..... $');
DECLARE (N, P) ADDRESS, C BASED P BYTE;
P = .S(5);
DIGIT:
P = P-1;
C = N MOD 10 + '0';
N = N / 10;
IF N > 0 THEN GO TO DIGIT;
CALL BDOS(9, P);
END PRINT$NUMBER;
 
/* SORT AN ARRAY */
DECLARE NUMBERS (11) ADDRESS INITIAL (4, 65, 2, 31, 0, 99, 2, 8, 3, 782, 1);
CALL HEAP$SORT(.NUMBERS, LENGTH(NUMBERS));
 
/* PRINT THE SORTED ARRAY */
DECLARE N BYTE;
DO N = 0 TO LAST(NUMBERS);
CALL PRINT$NUMBER(NUMBERS(N));
END;
 
CALL BDOS(0,0);
EOF</syntaxhighlight>
{{out}}
<pre>0 1 2 2 3 4 8 31 65 99 782</pre>
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
function heapsort($a, $count) {
$a = heapify $a $count
$end = $count - 1
while( $end -gt 0) {
$a[$end], $a[0] = $a[0], $a[$end]
$end--
$a = siftDown $a 0 $end
}
$a
}
function heapify($a, $count) {
$start = [Math]::Floor(($count - 2) / 2)
while($start -ge 0) {
$a = siftDown $a $start ($count-1)
$start--
}
$a
}
function siftdown($a, $start, $end) {
$b, $root = $true, $start
while(( ($root * 2 + 1) -le $end) -and $b) {
$child = $root * 2 + 1
if( ($child + 1 -le $end) -and ($a[$child] -lt $a[$child + 1]) ) {
$child++
}
if($a[$root] -lt $a[$child]) {
$a[$root], $a[$child] = $a[$child], $a[$root]
$root = $child
}
else { $b = $false}
}
$a
}
$array = @(60, 21, 19, 36, 63, 8, 100, 80, 3, 87, 11)
"$(heapsort $array $array.Count)"
</syntaxhighlight>
<b>Output:</b>
<pre>
3 8 11 19 21 36 60 63 80 87 100
</pre>
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Declare heapify(Array a(1), count)
Declare siftDown(Array a(1), start, ending)
 
Line 2,581 ⟶ 4,903:
EndIf
Wend
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">def heapsort(lst):
''' Heapsort. Note: this function sorts in-place (it mutates the list). '''
 
Line 2,607 ⟶ 4,929:
root = child
else:
break</langsyntaxhighlight>
Testing:
<pre>>>> ary = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
>>> heapsort(ary)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
 
=={{header|Quackery}}==
 
This uses code from [[Priority queue#Quackery]].
 
<syntaxhighlight lang="quackery"> [ [] swap pqwith >
dup pqsize times
[ frompq rot join swap ]
drop ] is hsort ( [ --> [ )
[] 23 times [ 90 random 10 + join ]
say " " dup echo cr
say " --> " hsort echo </syntaxhighlight>
 
''' Output:'''
<pre> [ 45 82 25 50 14 45 11 25 21 91 10 63 77 42 80 99 16 81 88 97 84 80 87 ]
--> [ 10 11 14 16 21 25 25 42 45 45 50 63 77 80 80 81 82 84 87 88 91 97 99 ]</pre>
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
(require (only-in srfi/43 vector-swap!))
Line 2,641 ⟶ 4,980:
(sift-down! 0 (- end 1)))
xs)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
<syntaxhighlight lang="raku" line>sub heap_sort ( @list ) {
for ( 0 ..^ +@list div 2 ).reverse -> $start {
_sift_down $start, @list.end, @list;
}
 
for ( 1 ..^ +@list ).reverse -> $end {
@list[ 0, $end ] .= reverse;
_sift_down 0, $end-1, @list;
}
}
 
sub _sift_down ( $start, $end, @list ) {
my $root = $start;
while ( my $child = $root * 2 + 1 ) <= $end {
$child++ if $child + 1 <= $end and [<] @list[ $child, $child+1 ];
return if @list[$root] >= @list[$child];
@list[ $root, $child ] .= reverse;
$root = $child;
}
}
 
my @data = 6, 7, 2, 1, 8, 9, 5, 3, 4;
say 'Input = ' ~ @data;
@data.&heap_sort;
say 'Output = ' ~ @data;</syntaxhighlight>
{{out}}
<pre>
Input = 6 7 2 1 8 9 5 3 4
Output = 1 2 3 4 5 6 7 8 9
</pre>
 
=={{header|REXX}}==
===version 1, elements of an array===
This REXX version uses a &nbsp; ''heapsort'' &nbsp; to sort elements of an array, thewhich elementsis canconstructed befrom numbersa list of words or strings.numbers,
<br>or a mixture of both.
<br>Indexing of the array (for this version) starts with &nbsp; '''1''' &nbsp; (one).
<lang rexx>/*REXX program sorts an array using the heapsort algorithm. */
call gen@ /*generate the array elements. */
call show@ 'before sort' /*show the before array elements*/
call heapSort # /*invoke the heap sort. */
call show@ ' after sort' /*show the after array elements*/
exit /*stick a fork in it, we're done.*/
/*──────────────────────────────────HEAPSORT subroutine─────────────────*/
heapSort: procedure expose @.; parse arg n; do j=n%2 by -1 to 1
call shuffle j,n
end /*j*/
do n=n by -1 to 2
_=@.1; @.1=@.n; @.n=_; call shuffle 1,n-1 /*swap and shuffle.*/
end /*n*/
return
/*──────────────────────────────────SHUFFLE subroutine──────────────────*/
shuffle: procedure expose @.; parse arg i,n; _=@.i
do while i+i<=n; j=i+i; k=j+1
if k<=n then if @.k>@.j then j=k
if _>=@.j then leave
@.i=@.j; i=j
end /*while*/
@.i=_
return
/*──────────────────────────────────GEN@ subroutine─────────────────────*/
gen@: @.=; @.1='---modern Greek alphabet letters---' /*default; title.*/
@.2= copies('=', length(@.1)) /*match sep with ↑*/
@.3='alpha' ; @.9 ='eta' ; @.15='nu' ; @.21='tau'
@.4='beta' ; @.10='theta' ; @.16='xi' ; @.22='upsilon'
@.5='gamma' ; @.11='iota' ; @.17='omicron' ; @.23='phi'
@.6='delta' ; @.12='kappa' ; @.18='pi' ; @.24='chi'
@.7='epsilon' ; @.13='lambd' ; @.19='rho' ; @.25='psi'
@.8='zeta' ; @.14='mu' ; @.20='sigma' ; @.26='omega'
 
Indexing of the array starts with &nbsp; '''1''' &nbsp; (one), &nbsp; but can be programmed to start with zero.
do #=1 while @.#\==''; end /*find how many entries in list. */
<syntaxhighlight lang="rexx">/*REXX pgm sorts an array (names of epichoric Greek letters) using a heapsort algorithm.*/
#=#-1 /*adjust highItem slightly. */
parse arg x; call init /*use args or default, define @ array.*/
return
call show "before sort:" /*#: the number of elements in array*/
/*──────────────────────────────────SHOW@ subroutine────────────────────*/
show@:call heapSort #; do j=1 for # say copies('▒', 40) /*sort; [↓]then after displaysort, elements inshow array.separator*/
call show " after sort:"
say ' element' right(j,length(#)) arg(1)':' @.j
exit end /*jstick a fork in it, we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
say copies('■', 70) /*show a separator line. */
init: _= 'alpha beta gamma delta digamma epsilon zeta eta theta iota kappa lambda mu nu' ,
return</lang>
"xi omicron pi san qoppa rho sigma tau upsilon phi chi psi omega"
{{out}} using the (default) Greek alphabet for input:
if x='' then x= _; #= words(x) /*#: number of words in X*/
<pre style="height:85ex">
do j=1 for #; @.j= word(x, j); end; return /*assign letters to array*/
element 1 before sort: ---modern Greek alphabet letters---
/*──────────────────────────────────────────────────────────────────────────────────────*/
element 2 before sort: ===================================
heapSort: procedure expose @.; arg n; do j=n%2 by -1 to 1; call shuffle j,n; end /*j*/
element 3 before sort: alpha
do n=n by -1 to 2; _= @.1; @.1= @.n; @.n= _; call heapSuff 1,n-1
element 4 before sort: beta
end /*n*/; return /* [↑] swap two elements; and shuffle.*/
element 5 before sort: gamma
/*──────────────────────────────────────────────────────────────────────────────────────*/
element 6 before sort: delta
heapSuff: procedure expose @.; parse arg i,n; $= @.i /*obtain parent.*/
element 7 before sort: epsilon
do while i+i<=n; j= i+i; k= j+1; if k<=n then if @.k>@.j then j= k
element 8 before sort: zeta
if $>=@.j then leave; @.i= @.j; i= j
element 9 before sort: eta
end /*while*/; @.i= $; return /*define lowest.*/
element 10 before sort: theta
/*──────────────────────────────────────────────────────────────────────────────────────*/
element 11 before sort: iota
show: do s=1 for #; say ' element' right(s, length(#)) arg(1) @.s; end; return</syntaxhighlight>
element 12 before sort: kappa
{{out|output|text=&nbsp; when using the default &nbsp; (epichoric Greek alphabet) &nbsp; for input:}}
element 13 before sort: lambda
(Shown at three-quarter size.)
element 14 before sort: mu
 
element 15 before sort: nu
<pre style="font-size:75%>
element 16 before sort: xi
element element 171 before sort: omicronalpha
element element 182 before sort: pibeta
element element 193 before sort: rhogamma
element element 204 before sort: sigmadelta
element element 215 before sort: taudigamma
element element 226 before sort: upsilonepsilon
element element 237 before sort: phizeta
element element 248 before sort: chieta
element element 259 before sort: psitheta
element 2610 before sort: omegaiota
element 11 before sort: kappa
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
element 12 1 afterbefore sort: ---modern Greek alphabet letters---lambda
element 13 2 afterbefore sort: ===================================mu
element 14 3 afterbefore sort: alphanu
element 15 4 afterbefore sort: betaxi
element 16 5 afterbefore sort: chiomicron
element 17 6 afterbefore sort: deltapi
element 18 7 afterbefore sort: epsilonsan
element 19 8 afterbefore sort: etaqoppa
element 20 9 afterbefore sort: gammarho
element 10 21 afterbefore sort: iotasigma
element 11 22 afterbefore sort: kappatau
element 12 23 afterbefore sort: lambdaupsilon
element 13 24 afterbefore sort: muphi
element 14 25 afterbefore sort: nuchi
element 15 26 afterbefore sort: omegapsi
element 16 27 afterbefore sort: omicronomega
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
element 17 after sort: phi
element element 181 after sort: pialpha
element element 192 after sort: psibeta
element element 203 after sort: rhochi
element element 214 after sort: sigmadelta
element element 225 after sort: taudigamma
element element 236 after sort: thetaepsilon
element element 247 after sort: upsiloneta
element element 258 after sort: xigamma
element element 269 after sort: zetaiota
element 10 after sort: kappa
■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
element 11 after sort: lambda
element 12 after sort: mu
element 13 after sort: nu
element 14 after sort: omega
element 15 after sort: omicron
element 16 after sort: phi
element 17 after sort: pi
element 18 after sort: psi
element 19 after sort: qoppa
element 20 after sort: rho
element 21 after sort: san
element 22 after sort: sigma
element 23 after sort: tau
element 24 after sort: theta
element 25 after sort: upsilon
element 26 after sort: xi
element 27 after sort: zeta
</pre>
{{out|output|text=&nbsp; when using the following for input: &nbsp; &nbsp; <tt> 19 &nbsp;0 &nbsp;-.2 &nbsp;.1 &nbsp;1e5 &nbsp;19 &nbsp;17 &nbsp;-6 &nbsp;789 &nbsp;11 &nbsp;37 </tt>}}
(Shown at three-quarter size.)
 
<pre style="font-size:75%">
element 1 before sort: 19
element 2 before sort: 0
element 3 before sort: -.2
element 4 before sort: .1
element 5 before sort: 1e5
element 6 before sort: 19
element 7 before sort: 17
element 8 before sort: -6
element 9 before sort: 789
element 10 before sort: 11
element 11 before sort: 37
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
element 1 after sort: -6
element 2 after sort: -.2
element 3 after sort: 0
element 4 after sort: .1
element 5 after sort: 11
element 6 after sort: 17
element 7 after sort: 19
element 8 after sort: 19
element 9 after sort: 37
element 10 after sort: 789
element 11 after sort: 1e5
</pre>
 
On an '''ASCII''' system, numbers are sorted &nbsp; ''before'' &nbsp; letters.
 
{{out|output|text=&nbsp; when executing on an &nbsp; '''ASCII''' &nbsp; system using the following for input: &nbsp; &nbsp; <tt> 11 &nbsp; 33 &nbsp; 22 &nbsp; scotoma &nbsp; pareidolia </tt>}}
<pre>
element 1 before sort: 11
element 2 before sort: 33
element 3 before sort: 22
element 4 before sort: scotoma
element 5 before sort: pareidolia
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
element 1 after sort: 11
element 2 after sort: 22
element 3 after sort: 33
element 4 after sort: pareidolia
element 5 after sort: scotoma
</pre>
 
On an '''EBCDIC''' system, numbers are sorted &nbsp; ''after'' &nbsp; letters.
 
{{out|output|text=&nbsp; when executing on an &nbsp; '''EBCDIC''' &nbsp; system using the following for input: &nbsp; &nbsp; <tt> 11 &nbsp; 33 &nbsp; 22 &nbsp; scotoma &nbsp; pareidolia</tt>}}
<pre>
element 1 before sort: 11
element 2 before sort: 33
element 3 before sort: 22
element 4 before sort: scotoma
element 5 before sort: pareidolia
▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒
element 1 after sort: pareidolia
element 2 after sort: scotoma
element 3 after sort: 11
element 4 after sort: 22
element 5 after sort: 33
</pre>
 
=== Versionversion 2 ===
<langsyntaxhighlight lang="rexx">/* REXX ***************************************************************
* Translated from PL/I
* 27.07.2013 Walter Pachl
Line 2,819 ⟶ 5,238:
Say 'element' format(j,2) txt a.j
End
Return</langsyntaxhighlight>
Output: see PL/I
 
=={{header|Ring}}==
<syntaxhighlight lang="ring">
# Project : Sorting algorithms/Heapsort
 
test = [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
see "before sort:" + nl
showarray(test)
heapsort(test)
see "after sort:" + nl
showarray(test)
func heapsort(a)
cheapify(a)
for e = len(a) to 1 step -1
temp = a[e]
a[e] = a[1]
a[1] = temp
siftdown(a, 1, e-1)
next
func cheapify(a)
m = len(a)
for s = floor((m - 1) / 2) to 1 step -1
siftdown(a,s,m)
next
func siftdown(a,s,e)
r = s
while r * 2 + 1 <= e
c = r * 2
if c + 1 <= e
if a[c] < a[c + 1]
c = c + 1
ok
ok
if a[r] < a[c]
temp = a[r]
a[r] = a[c]
a[c] = temp
r = c
else
exit
ok
end
 
func showarray(vect)
svect = ""
for n = 1 to len(vect)
svect = svect + vect[n] + " "
next
svect = left(svect, len(svect) - 1)
see svect + nl
</syntaxhighlight>
Output:
<pre>
before sort:
4 65 2 -31 0 99 2 83 782 1
after sort:
-31 0 1 2 2 4 65 83 99 782
</pre>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Array
def heapsort
self.dup.heapsort!
Line 2,856 ⟶ 5,336:
end
end
end</langsyntaxhighlight>
Testing:
<pre>irb(main):035:0> ary = [7, 6, 5, 9, 8, 4, 3, 1, 2, 0]
Line 2,862 ⟶ 5,342:
irb(main):036:0> ary.heapsort
=> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
 
=={{header|Rust}}==
{{trans|Python}}
This program allows the caller to specify an arbitrary function by which an order is determined.
<syntaxhighlight lang="rust">fn main() {
let mut v = [4, 6, 8, 1, 0, 3, 2, 2, 9, 5];
heap_sort(&mut v, |x, y| x < y);
println!("{:?}", v);
}
 
fn heap_sort<T, F>(array: &mut [T], order: F)
where
F: Fn(&T, &T) -> bool,
{
let len = array.len();
// Create heap
for start in (0..len / 2).rev() {
shift_down(array, &order, start, len - 1)
}
 
for end in (1..len).rev() {
array.swap(0, end);
shift_down(array, &order, 0, end - 1)
}
}
 
fn shift_down<T, F>(array: &mut [T], order: &F, start: usize, end: usize)
where
F: Fn(&T, &T) -> bool,
{
let mut root = start;
loop {
let mut child = root * 2 + 1;
if child > end {
break;
}
if child + 1 <= end && order(&array[child], &array[child + 1]) {
child += 1;
}
if order(&array[root], &array[child]) {
array.swap(root, child);
root = child
} else {
break;
}
}
}</syntaxhighlight>
 
Of course, you could also simply use <code>BinaryHeap</code> in the standard library.
 
<syntaxhighlight lang="rust">use std::collections::BinaryHeap;
 
fn main() {
let src = vec![6, 2, 3, 6, 1, 2, 7, 8, 3, 2];
let sorted = BinaryHeap::from(src).into_sorted_vec();
println!("{:?}", sorted);
}</syntaxhighlight>
 
=={{header|Scala}}==
{{works with|Scala|2.8}}
This code is not written for maximum performance, though, of course, it preserves the O(n log n) characteristic of heap sort.
<langsyntaxhighlight lang="scala">def heapSort[T](a: Array[T])(implicit ord: Ordering[T]) {
import scala.annotation.tailrec // Ensure functions are tail-recursive
import ord._
Line 2,907 ⟶ 5,444:
siftDown(0, i)
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
{{works with|Scheme|R<math>^5</math>RS}}
<langsyntaxhighlight lang="scheme">; swap two elements of a vector
(define (swap! v i j)
(define temp (vector-ref v i))
Line 2,964 ⟶ 5,501:
(define uriah (list->vector '(3 5 7 9 0 8 1 4 2 6)))
(heapsort uriah)
uriah</langsyntaxhighlight>
{{out}}
<pre>done
Line 2,970 ⟶ 5,507:
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">const proc: downheap (inout array elemType: arr, in var integer: k, in integer: n) is func
local
var elemType: help is elemType.value;
Line 3,008 ⟶ 5,545:
downheap(arr, 1, n);
until n <= 1;
end func;</langsyntaxhighlight>
Original source: [http://seed7.sourceforge.net/algorith/sorting.htm#heapSort]
 
=={{header|SequenceL}}==
<syntaxhighlight lang="sequencel">
import <Utilities/Sequence.sl>;
 
TUPLE<T> ::= (A: T, B: T);
 
heapSort(x(1)) :=
let
heapified := heapify(x, (size(x) - 2) / 2 + 1);
in
sortLoop(heapified, size(heapified));
 
heapify(x(1), i) :=
x when i <= 0 else
heapify(siftDown(x, i, size(x)), i - 1);
 
sortLoop(x(1), i) :=
x when i <= 2 else
sortLoop( siftDown(swap(x, 1, i), 1, i - 1), i - 1);
 
siftDown(x(1), start, end) :=
let
child := start * 2;
child1 := child + 1 when child + 1 <= end and x[child] < x[child + 1] else child;
in
x when child >= end else
x when x[start] >= x[child1] else
siftDown(swap(x, child1, start), child1, end);
 
swap(list(1), i, j) :=
let
vals := (A: list[i], B: list[j]);
in
setElementAt(setElementAt(list, i, vals.B), j, vals.A);
</syntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">func siftDownsift_down(a, start, end) {
var root = start;
while ((2*root + 1) <= end) {
var child = (2*root + 1);
if ((child+1 <= end) && (a[child] < a[child + 1])) {
child += 1;
};
if (a[root] < a[child]) {
a[child, root] = a[root, child];
root = child;
} else {
return; nil
}
}
Line 3,029 ⟶ 5,602:
 
func heapify(a, count) {
var start = ((count - 2) / 2);
while (start >= 0) {
siftDownsift_down(a, start, count-1);
start -= 1;
}
}
 
func heapSortheap_sort(a, count) {
heapify(a, count);
var end = (count - 1);
while (end > 0) {
a[0, end] = a[end, 0];
end -= 1;
siftDownsift_down(a, 0, end)
}
return a
}
 
var arr = (1..10 -> shuffle); # creates a shuffled array
say arr.dump; # prints the unsorted array
heapSortheap_sort(arr, arr.len); # sorts the array in-place
say arr.dump; # prints the sorted array</langsyntaxhighlight>
{{out}}
<pre>[10, 5, 2, 1, 7, 6, 4, 8, 3, 9]
Line 3,058 ⟶ 5,632:
Since Standard ML is a functional language, a [http://en.wikipedia.org/wiki/Pairing_heap pairing heap] is used instead of a standard binary heap.
 
<langsyntaxhighlight lang="sml">(* Pairing heap - http://en.wikipedia.org/wiki/Pairing_heap *)
functor PairingHeap(type t
val cmp : t * t -> order) =
Line 3,112 ⟶ 5,686:
val test_3 = heapsort [6,2,7,5,8,1,3,4] = [1, 2, 3, 4, 5, 6, 7, 8]
end;
</syntaxhighlight>
</lang>
 
=={{header|Stata}}==
 
Variant with siftup and siftdown, using Mata.
 
<syntaxhighlight lang="mata">function siftup(a, i) {
k = i
while (k > 1) {
p = floor(k/2)
if (a[k] > a[p]) {
s = a[p]
a[p] = a[k]
a[k] = s
k = p
}
else break
}
}
 
function siftdown(a, i) {
k = 1
while (1) {
l = k+k
if (l > i) break
if (l+1 <= i) {
if (a[l+1] > a[l]) l++
}
if (a[k] < a[l]) {
s = a[k]
a[k] = a[l]
a[l] = s
k = l
}
else break
}
}
 
function heapsort(a) {
n = length(a)
for (i = 2; i <= n; i++) {
siftup(a, i)
}
for (i = n; i >= 2; i--) {
s = a[i]
a[i] = a[1]
a[1] = s
siftdown(a, i-1)
}
}</syntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight Swiftlang="swift">func heapsort<T:Comparable>(inout list:[T]) {
var count = list.count
Line 3,162 ⟶ 5,786:
shiftDown(&list, 0, end)
}
}</langsyntaxhighlight>
 
=={{header|Tcl}}==
Based on the algorithm from Wikipedia:
{{works with|Tcl|8.5}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
 
proc heapsort {list {count ""}} {
Line 3,205 ⟶ 5,829:
lset a $x [lindex $a $y]
lset a $y $tmp
}</langsyntaxhighlight>
Demo code:
<langsyntaxhighlight lang="tcl">puts [heapsort {1 5 3 7 9 2 8 4 6 0}]</langsyntaxhighlight>
{{out}}
<pre>0 1 2 3 4 5 6 7 8 9</pre>
 
=={{header|TI-83 BASIC}}==
Store list with a dimension of 7 or less into L<sub>1</sub> (if less input will be padded with zeros), run prgmSORTHEAP, look into L<sub>2</sub> for the sorted version of L<sub>1</sub>. It is possible to do this without L<sub>3</sub> (thus, in place), but I coded this when I was paying attention to a math lecture. Could you make a better version that accepts any input, without having to use my clunky <code>If</code> structure? Could you make it in-place?
 
:If dim(L<sub>1</sub>)>7
:Then
Line 3,281 ⟶ 5,906:
:DelVar L<sub>3</sub>
:Return
 
 
=={{header|True BASIC}}==
{{trans|Liberty BASIC}}
<syntaxhighlight lang="qbasic">
!creamos la matriz y la inicializamos
LET lim = 20
DIM array(20)
FOR i = 1 TO lim
LET array(i) = INT(RND * 100) + 1
NEXT i
 
SUB printArray (lim)
FOR i = 1 TO lim
!PRINT using("###", array(i));
PRINT array(i); " ";
NEXT i
PRINT
END SUB
 
SUB heapify (count)
LET start = INT(count / 2)
DO WHILE start >= 1
CALL siftDown (start, count)
LET start = start - 1
LOOP
END SUB
 
SUB siftDown (inicio, final)
LET root = inicio
DO WHILE root * 2 <= final
LET child = root * 2
LET SWAP = root
IF array(SWAP) < array(child) THEN
LET SWAP = child
END IF
IF child+1 <= final THEN
IF array(SWAP) < array(child+1) THEN
LET SWAP = child + 1
END IF
END IF
IF SWAP <> root THEN
CALL SWAP (root, SWAP)
LET root = SWAP
ELSE
EXIT SUB
END IF
LOOP
END SUB
 
SUB SWAP (x,y)
LET tmp = array(x)
LET array(x) = array(y)
LET array(y) = tmp
END SUB
 
SUB heapSort (count)
CALL heapify (count)
 
PRINT "el montículo:"
CALL printArray (count)
 
LET final = count
DO WHILE final > 1
CALL SWAP (final, 1)
CALL siftDown (1, final-1)
LET final = final - 1
LOOP
END SUB
 
!--------------------------
PRINT "Antes de ordenar:"
CALL printArray (lim)
PRINT
CALL heapSort (lim)
PRINT
PRINT "Despues de ordenar:"
CALL printArray (lim)
END
</syntaxhighlight>
 
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">PRINT "Heap sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
PROC _Heapsort (n)
PROC _ShowArray (n)
PRINT
 
END
 
 
_Heapsort PARAM(1) ' Heapsort
LOCAL(1)
PROC _Heapify (a@)
 
b@ = a@ - 1
DO WHILE b@ > 0
PROC _Swap (b@, 0)
PROC _Siftdown (0, b@)
b@ = b@ - 1
LOOP
RETURN
 
 
_Heapify PARAM(1)
LOCAL(1)
 
b@ = (a@ - 2) / 2
DO WHILE b@ > -1
PROC _Siftdown (b@, a@)
b@ = b@ - 1
LOOP
RETURN
 
 
_Siftdown PARAM(2)
LOCAL(2)
c@ = a@
 
DO WHILE ((c@ * 2) + 1) < (b@)
d@ = c@ * 2 + 1
IF d@+1 < b@ IF @(d@) < @(d@+1) THEN d@ = d@ + 1
WHILE @(c@) < @(d@)
PROC _Swap (d@, c@)
c@ = d@
LOOP
 
RETURN
 
 
_Swap PARAM(2) ' Swap two array elements
PUSH @(a@)
@(a@) = @(b@)
@(b@) = POP()
RETURN
 
 
_InitArray ' Init example array
PUSH 4, 65, 2, -31, 0, 99, 2, 83, 782, 1
 
FOR i = 0 TO 9
@(i) = POP()
NEXT
 
RETURN (i)
 
 
_ShowArray PARAM (1) ' Show array subroutine
FOR i = 0 TO a@-1
PRINT @(i),
NEXT
 
PRINT
RETURN</syntaxhighlight>
 
=={{header|Vala}}==
{{trans|C++}}
<syntaxhighlight lang="vala">void swap(int[] array, int i1, int i2) {
if (array[i1] == array[i2])
return;
var tmp = array[i1];
array[i1] = array[i2];
array[i2] = tmp;
}
 
void shift_down(int[] heap, int i, int max) {
int i_big, c1, c2;
while (i < max) {
i_big = i;
c1 = (2 * i) + 1;
c2 = c1 + 1;
if (c1 < max && heap[c1] > heap[i_big])
i_big = c1;
if (c2 < max && heap[c2] > heap[i_big])
i_big = c2;
if (i_big == i) return;
swap(heap, i, i_big);
i = i_big;
}
}
 
void to_heap(int[] array) {
int i = (array.length / 2) - 1;
while (i >= 0) {
shift_down(array, i, array.length);
--i;
}
}
 
void heap_sort(int[] array) {
to_heap(array);
int end = array.length - 1;
while (end > 0) {
swap(array, 0, end);
shift_down(array, 0, end);
--end;
}
}
 
void main() {
int[] data = {
12, 11, 15, 10, 9,
1, 2, 13, 3, 14,
4, 5, 6, 7, 8
};
heap_sort(data);
foreach (int i in data) {
stdout.printf("%d ", i);
}
}</syntaxhighlight>
 
{{out}}
<pre>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
</pre>
 
=={{header|VBA}}==
{{trans|FreeBASIC}}
<syntaxhighlight lang="vba">Sub SiftDown(list() As Integer, start As Long, eend As Long)
Dim root As Long : root = start
Dim lb As Long : lb = LBound(list)
Dim temp As Integer
 
While root * 2 + 1 <= eend
Dim child As Long : child = root * 2 + 1
If child + 1 <= eend Then
If list(lb + child) < list(lb + child + 1) Then
child = child + 1
End If
End If
If list(lb + root) < list(lb + child) Then
temp = list(lb + root)
list(lb + root) = list(lb + child)
list(lb + child) = temp
 
root = child
Else
Exit Sub
End If
Wend
End Sub
 
Sub HeapSort(list() As Integer)
Dim lb As Long : lb = LBound(list)
Dim count As Long : count = UBound(list) - lb + 1
Dim start As Long : start = (count - 2) \ 2
Dim eend As Long : eend = count - 1
 
While start >= 0
SiftDown list(), start, eend
start = start - 1
Wend
Dim temp As Integer
 
While eend > 0
temp = list(lb + eend)
list(lb + eend) = list(lb)
list(lb) = temp
 
eend = eend - 1
 
SiftDown list(), 0, eend
Wend
End Sub</syntaxhighlight>
 
=={{header|V (Vlang)}}==
<syntaxhighlight lang="v (vlang)">
fn main() {
mut test_arr := [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
println('Before : $test_arr')
heap_sort(mut test_arr) // Heap Sort
println('After : $test_arr')
}
 
[direct_array_access]
fn heap_sort(mut array []int) {
n := array.len
for i := n/2; i > -1; i-- {
heapify(mut array, n, i) // Max heapify
}
for i := n - 1; i > 0; i-- {
array[i], array[0] = array[0], array[i]
heapify(mut array, i, 0)
}
}
 
[direct_array_access]
fn heapify(mut array []int, n int, i int) {
mut largest := i
left := 2 * i + 1
right := 2 * i + 2
if left < n && array[i] < array[left] {
largest = left
}
if right < n && array[largest] < array[right] {
largest = right
}
if largest != i {
array[i], array[largest] = array[largest], array[i]
heapify(mut array, n, largest)
}
}
</syntaxhighlight>
 
{{out}}
<pre>
Before : [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
After : [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]
</pre>
 
=={{header|Wren}}==
<syntaxhighlight lang="wren">var siftDown = Fn.new { |a, start, end|
var root = start
while (root*2 + 1 <= end) {
var child = root*2 + 1
if (child + 1 <= end && a[child] < a[child+1]) child = child + 1
if (a[root] < a[child]) {
var t = a[root]
a[root] = a[child]
a[child] = t
root = child
} else {
return
}
}
}
 
var heapify = Fn.new { |a, count|
var start = ((count - 2)/2).floor
while (start >= 0) {
siftDown.call(a, start, count - 1)
start = start - 1
}
}
 
var heapSort = Fn.new { |a|
var count = a.count
heapify.call(a, count)
var end = count - 1
while (end > 0) {
var t = a[end]
a[end] = a[0]
a[0] = t
end = end - 1
siftDown.call(a, 0, end)
}
}
 
var array = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in array) {
System.print("Before: %(a)")
heapSort.call(a)
System.print("After : %(a)")
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
Before: [4, 65, 2, -31, 0, 99, 2, 83, 782, 1]
After : [-31, 0, 1, 2, 2, 4, 65, 83, 99, 782]
 
Before: [7, 5, 2, 6, 1, 4, 2, 6, 3]
After : [1, 2, 2, 3, 4, 5, 6, 6, 7]
</pre>
<br>
Alternatively, we can just call a library method.
{{libheader|Wren-sort}}
<syntaxhighlight lang="wren">import "./sort" for Sort
 
var array = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in array) {
System.print("Before: %(a)")
Sort.heap(a)
System.print("After : %(a)")
System.print()
}</syntaxhighlight>
 
{{out}}
<pre>
As above.
</pre>
 
=={{header|XPL0}}==
<syntaxhighlight lang "XPL0">proc HeapSort(Array, Size);
int Array, Size;
int First, Last, T;
 
proc Sift(First, Count);
int First, Count;
int Root, Child, T;
[Root:= First;
loop [if Root*2 + 1 >= Count then quit;
Child:= Root*2 + 1;
if Child < Count-1 and Array(Child) < Array(Child+1) then
Child:= Child+1;
if Array(Root) < Array(Child) then
[T:= Array(Root); Array(Root):= Array(Child); Array(Child):= T;
Root:= Child;
]
else quit;
];
];
 
[First:= (Size-1)/2 - 1;
Last:= Size-1;
while First >= 0 do
[Sift(First, Size-1);
First:= First-1;
];
while Last > 0 do
[T:= Array(Last); Array(Last):= Array(0); Array(0):= T;
Sift(0, Last);
Last:= Last-1;
];
];
 
int Array, Size, I;
[Array:= [4, 65, 2, 31, 0, 99, 2, 8, 3, 782, 1];
Size:= 11;
HeapSort(Array, Size);
for I:= 0, Size-1 do
[IntOut(0, Array(I)); ChOut(0, ^ )];
]</syntaxhighlight>
{{out}}
<pre>
0 1 2 2 3 4 8 31 65 99 782 </pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn heapSort(a){ // in place
n := a.len();
foreach start in ([(n-2)/2 .. 0,-1])
Line 3,301 ⟶ 6,355:
start = child;
}
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">heapSort(L(170, 45, 75, -90, -802, 24, 2, 66)).println();
heapSort("this is a test".split("")).println();</langsyntaxhighlight>
{{out}}
<pre>
9,479

edits