How to resolve the algorithm Sorting algorithms/Heapsort step by step in the Wren programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Heapsort step by step in the Wren 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 Wren programming language
Source code in the wren programming language
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 as = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in as) {
System.print("Before: %(a)")
heapSort.call(a)
System.print("After : %(a)")
System.print()
}
import "/sort" for Sort
var as = [ [4, 65, 2, -31, 0, 99, 2, 83, 782, 1], [7, 5, 2, 6, 1, 4, 2, 6, 3] ]
for (a in as) {
System.print("Before: %(a)")
Sort.heap(a)
System.print("After : %(a)")
System.print()
}
You may also check:How to resolve the algorithm Jewels and stones step by step in the Raku programming language
You may also check:How to resolve the algorithm Idiomatically determine all the lowercase and uppercase letters step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Golden ratio/Convergence step by step in the Ol programming language
You may also check:How to resolve the algorithm Elementary cellular automaton step by step in the Scala programming language
You may also check:How to resolve the algorithm Environment variables step by step in the Oforth programming language