How to resolve the algorithm Sorting algorithms/Merge sort step by step in the BCPL programming language
How to resolve the algorithm Sorting algorithms/Merge sort step by step in the BCPL 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 BCPL programming language
Source code in the bcpl programming language
get "libhdr"
let mergesort(A, n) be if n >= 2
$( let m = n / 2
mergesort(A, m)
mergesort(A+m, n-m)
merge(A, n, m)
$)
and merge(A, n, m) be
$( let i, j = 0, m
let x = getvec(n)
for k=0 to n-1
x!k := A!valof
test j~=n & (i=m | A!j < A!i)
$( j := j + 1
resultis j - 1
$)
else
$( i := i + 1
resultis i - 1
$)
for i=0 to n-1 do a!i := x!i
freevec(x)
$)
let write(s, A, len) be
$( writes(s)
for i=0 to len-1 do writed(A!i, 4)
wrch('*N')
$)
let start() be
$( let array = table 4,65,2,-31,0,99,2,83,782,1
let length = 10
write("Before: ", array, length)
mergesort(array, length)
write("After: ", array, length)
$)
You may also check:How to resolve the algorithm Quine step by step in the Free Pascal programming language
You may also check:How to resolve the algorithm Rock-paper-scissors step by step in the Perl programming language
You may also check:How to resolve the algorithm Align columns step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Undefined values step by step in the ERRE programming language
You may also check:How to resolve the algorithm Anti-primes step by step in the 8086 Assembly programming language