How to resolve the algorithm Sorting algorithms/Merge sort step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

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

Source code in the nim programming language

proc merge[T](a, b: var openarray[T]; left, middle, right: int) =
  let
    leftLen = middle - left
    rightLen = right - middle
  var
    l = 0
    r = leftLen
 
  for i in left ..< middle:
    b[l] = a[i]
    inc l
  for i in middle ..< right:
    b[r] = a[i]
    inc r
 
  l = 0
  r = leftLen
  var i = left
 
  while l < leftLen and r < leftLen + rightLen:
    if b[l] < b[r]:
      a[i] = b[l]
      inc l
    else:
      a[i] = b[r]
      inc r
    inc i
 
  while l < leftLen:
    a[i] = b[l]
    inc l
    inc i
  while r < leftLen + rightLen:
    a[i] = b[r]
    inc r
    inc i
 
proc mergeSort[T](a, b: var openarray[T]; left, right: int) =
  if right - left <= 1: return
 
  let middle = (left + right) div 2
  mergeSort(a, b, left, middle)
  mergeSort(a, b, middle, right)
  merge(a, b, left, middle, right)
 
proc mergeSort[T](a: var openarray[T]) =
  var b = newSeq[T](a.len)
  mergeSort(a, b, 0, a.len)
 
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
mergeSort a
echo a


  

You may also check:How to resolve the algorithm Langton's ant step by step in the MATLAB / Octave programming language
You may also check:How to resolve the algorithm Caesar cipher step by step in the Scheme programming language
You may also check:How to resolve the algorithm Evaluate binomial coefficients step by step in the Raku programming language
You may also check:How to resolve the algorithm Anonymous recursion step by step in the Qi programming language
You may also check:How to resolve the algorithm Accumulator factory step by step in the Oz programming language