Sorting algorithms/Heapsort: Difference between revisions

{{header|Liberty BASIC}}
(→‎{{header|Go}}: added more generic version)
({{header|Liberty BASIC}})
Line 1,028:
}</lang>
 
=={{header|Liberty BASIC}}==
<lang lb>wikiSample=1 'comment out for random array
 
data 6, 5, 3, 1, 8, 7, 2, 4
itemCount = 20
if wikiSample then itemCount = 8
dim A(itemCount)
for i = 1 to itemCount
A(i) = int(rnd(1) * 100)
if wikiSample then read tmp: A(i)=tmp
next i
 
print "Before Sort"
call printArray itemCount
 
call heapSort itemCount
 
print "After Sort"
call printArray itemCount
end
 
'------------------------------------------
sub heapSort count
call heapify count
 
print "the heap"
call printArray count
 
theEnd = count
while theEnd > 1
call swap theEnd, 1
call siftDown 1, theEnd-1
theEnd = theEnd - 1
wend
end sub
 
sub heapify count
start = int(count / 2)
while start >= 1
call siftDown start, count
start = start - 1
wend
end sub
 
sub siftDown start, theEnd
root = start
while root * 2 <= theEnd
child = root * 2
swap = root
if A(swap) < A(child) then
swap = child
end if
if child+1 <= theEnd then
if A(swap) < A(child+1) then
swap = child + 1
end if
end if
if swap <> root then
call swap root, swap
root = swap
else
exit sub
end if
wend
end sub
 
sub swap a,b
tmp = A(a)
A(a) = A(b)
A(b) = tmp
end sub
 
'===========================================
sub printArray itemCount
for i = 1 to itemCount
print using("###", A(i));
next i
print
end sub
</lang>
 
=={{header|M4}}==
Anonymous user