How to resolve the algorithm Sorting algorithms/Heapsort step by step in the Liberty BASIC programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Heapsort step by step in the Liberty BASIC programming language
Table of Contents
Problem Statement
Heapsort is an in-place sorting algorithm with worst case and average complexity of O(n logn). 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. A heap sort requires random access, so can only be used on an array-like data structure. Pseudocode:
Write a function to sort a collection of integers using heapsort.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sorting algorithms/Heapsort step by step in the Liberty BASIC programming language
Source code in the liberty programming language
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
You may also check:How to resolve the algorithm Möbius function step by step in the Fortran programming language
You may also check:How to resolve the algorithm Ranking methods step by step in the Visual FoxPro programming language
You may also check:How to resolve the algorithm Repeat a string step by step in the Tailspin programming language
You may also check:How to resolve the algorithm Sorting algorithms/Shell sort step by step in the jq programming language
You may also check:How to resolve the algorithm Entropy step by step in the jq programming language