How to resolve the algorithm Sorting algorithms/Merge sort step by step in the Maxima programming language
How to resolve the algorithm Sorting algorithms/Merge sort step by step in the Maxima programming language
Table of Contents
Problem Statement
The merge sort is a recursive sort of order nlog(n). It is notable for having a worst case and average complexity of O(nlog(n)), and a best case complexity of O(n) (for pre-sorted input). The basic idea is to split the collection into smaller groups by halving it until the groups only have one element or no elements (which are both entirely sorted groups). Then merge the groups back together so that their elements are in order. This is how the algorithm gets its divide and conquer description.
Write a function to sort a collection of integers using the merge sort.
The merge sort algorithm comes in two parts: The functions in pseudocode look like this:
Note: better performance can be expected if, rather than recursing until length(m) ≤ 1, an insertion sort is used for length(m) smaller than some threshold larger than 1. However, this complicates the example code, so it is not shown here.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Sorting algorithms/Merge sort step by step in the Maxima programming language
Source code in the maxima programming language
merge(a, b) := block(
[c: [ ], i: 1, j: 1, p: length(a), q: length(b)],
while i <= p and j <= q do (
if a[i] < b[j] then (
c: endcons(a[i], c),
i: i + 1
) else (
c: endcons(b[j], c),
j: j + 1
)
),
if i > p then append(c, rest(b, j - 1)) else append(c, rest(a, i - 1))
)$
mergesort(u) := block(
[n: length(u), k, a, b],
if n <= 1 then u else (
a: rest(u, k: quotient(n, 2)),
b: rest(u, k - n),
merge(mergesort(a), mergesort(b))
)
)$
You may also check:How to resolve the algorithm Monty Hall problem step by step in the Emacs Lisp programming language
You may also check:How to resolve the algorithm Input loop step by step in the LSL programming language
You may also check:How to resolve the algorithm Fractran step by step in the Bracmat programming language
You may also check:How to resolve the algorithm Sorting algorithms/Gnome sort step by step in the Lua programming language
You may also check:How to resolve the algorithm Compile-time calculation step by step in the PowerShell programming language