How to resolve the algorithm Sorting algorithms/Heapsort step by step in the Racket programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Sorting algorithms/Heapsort step by step in the Racket 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 Racket programming language
Source code in the racket programming language
#lang racket
(require (only-in srfi/43 vector-swap!))
(define (heap-sort! xs)
(define (ref i) (vector-ref xs i))
(define (swap! i j) (vector-swap! xs i j))
(define size (vector-length xs))
(define (sift-down! r end)
(define c (+ (* 2 r) 1))
(define c+1 (+ c 1))
(when (<= c end)
(define child
(if (and (<= c+1 end) (< (ref c) (ref c+1)))
c+1 c))
(when (< (ref r) (ref child))
(swap! r child))
(sift-down! child end)))
(for ([i (in-range (quotient (- size 2) 2) -1 -1)])
(sift-down! i (- size 1)))
(for ([end (in-range (- size 1) 0 -1)])
(swap! 0 end)
(sift-down! 0 (- end 1)))
xs)
You may also check:How to resolve the algorithm Own digits power sum step by step in the Go programming language
You may also check:How to resolve the algorithm Price fraction step by step in the Ruby programming language
You may also check:How to resolve the algorithm Diversity prediction theorem step by step in the Racket programming language
You may also check:How to resolve the algorithm Tokenize a string step by step in the Nanoquery programming language
You may also check:How to resolve the algorithm Order by pair comparisons step by step in the Julia programming language