How to resolve the algorithm Sorting algorithms/Heapsort step by step in the zkl programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sorting algorithms/Heapsort step by step in the zkl 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 zkl programming language

Source code in the zkl programming language

fcn heapSort(a){  // in place
   n := a.len();
   foreach start in ([(n-2)/2 .. 0,-1])
      { siftDown(a, start, n-1) }
   foreach end in ([n-1 .. 1,-1]){
      a.swap(0, end);
      siftDown(a, 0, end-1);
   }
   a
}

fcn siftDown(a, start, end){
   while((child := start*2 + 1) <= end){
      if(child < end and a[child]
      if(a[start] >= a[child]) return();
      a.swap(start, child);
      start = child;
   }
}

heapSort(L(170, 45, 75, -90, -802, 24, 2, 66)).println();
heapSort("this is a test".split("")).println();

  

You may also check:How to resolve the algorithm Bulls and cows step by step in the Python programming language
You may also check:How to resolve the algorithm Longest increasing subsequence step by step in the 360 Assembly programming language
You may also check:How to resolve the algorithm Cumulative standard deviation step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Retrieve and search chat history step by step in the zkl programming language
You may also check:How to resolve the algorithm Smallest number k such that k+2^m is composite for all m less than k step by step in the Mathematica/Wolfram Language programming language