How to resolve the algorithm Sorting algorithms/Merge sort step by step in the Prolog programming language
How to resolve the algorithm Sorting algorithms/Merge sort step by step in the Prolog 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 Prolog programming language
Source code in the prolog programming language
% msort( L, S )
% True if S is a sorted copy of L, using merge sort
msort( [], [] ).
msort( [X], [X] ).
msort( U, S ) :- split(U, L, R), msort(L, SL), msort(R, SR), merge(SL, SR, S).
% split( LIST, L, R )
% Alternate elements of LIST in L and R
split( [], [], [] ).
split( [X], [X], [] ).
split( [L,R|T], [L|LT], [R|RT] ) :- split( T, LT, RT ).
% merge( LS, RS, M )
% Assuming LS and RS are sorted, True if M is the sorted merge of the two
merge( [], RS, RS ).
merge( LS, [], LS ).
merge( [L|LS], [R|RS], [L|T] ) :- L =< R, merge( LS, [R|RS], T).
merge( [L|LS], [R|RS], [R|T] ) :- L > R, merge( [L|LS], RS, T).
You may also check:How to resolve the algorithm Increment a numerical string step by step in the K programming language
You may also check:How to resolve the algorithm Special variables step by step in the FreeBASIC programming language
You may also check:How to resolve the algorithm Pernicious numbers step by step in the S-lang programming language
You may also check:How to resolve the algorithm String append step by step in the Euphoria programming language
You may also check:How to resolve the algorithm Extreme floating point values step by step in the FreeBASIC programming language