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

Published on 12 May 2024 09:40 PM

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

Source code in the scala programming language

import scala.language.implicitConversions

object MergeSort extends App {

  def mergeSort(input: List[Int]): List[Int] = {
    def merge(left: List[Int], right: List[Int]): LazyList[Int] = (left, right) match {
      case (x :: xs, y :: ys) if x <= y => x #:: merge(xs, right)
      case (x :: xs, y :: ys) => y #:: merge(left, ys)
      case _ => if (left.isEmpty) right.to(LazyList) else left.to(LazyList)
    }

    def sort(input: List[Int], length: Int): List[Int] = input match {
      case Nil | List(_) => input
      case _ =>
        val middle = length / 2
        val (left, right) = input splitAt middle
        merge(sort(left, middle), sort(right, middle + length % 2)).toList
    }

    sort(input, input.length)
  }

}

  

You may also check:How to resolve the algorithm Hello world/Graphical step by step in the Frege programming language
You may also check:How to resolve the algorithm Partial function application step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Zero to the zero power step by step in the NewLISP programming language
You may also check:How to resolve the algorithm Sleeping Beauty problem step by step in the Java programming language
You may also check:How to resolve the algorithm Sum and product puzzle step by step in the Common Lisp programming language