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

Published on 12 May 2024 09:40 PM

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

Table of Contents

Problem Statement

Sort an array of elements using the Shell sort algorithm, a diminishing increment sort. The Shell sort   (also known as Shellsort or Shell's method)   is named after its inventor, Donald Shell, who published the algorithm in 1959. Shell sort is a sequence of interleaved insertion sorts based on an increment sequence. The increment size is reduced after each pass until the increment size is 1. With an increment size of 1, the sort is a basic insertion sort, but by this time the data is guaranteed to be almost sorted, which is insertion sort's "best case". Any sequence will sort the data as long as it ends in 1, but some work better than others. Empirical studies have shown a geometric increment sequence with a ratio of about 2.2 work well in practice. [1] Other good sequences are found at the On-Line Encyclopedia of Integer Sequences.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Sorting algorithms/Shell sort step by step in the Scala programming language

Source code in the scala programming language

object ShellSort {
  def incSeq(len:Int)=new Iterator[Int]{
    private[this] var x:Int=len/2
    def hasNext=x>0
    def next()={x=if (x==2) 1 else x*5/11; x}
  }

  def InsertionSort(a:Array[Int], inc:Int)={
    for (i <- inc until a.length; temp=a(i)){ 
      var j=i;
      while (j>=inc && a(j-inc)>temp){ 
        a(j)=a(j-inc)
        j=j-inc
      }
      a(j)=temp
    }
  }
  
  def shellSort(a:Array[Int])=for(inc<-incSeq(a.length)) InsertionSort(a, inc)
  
  def main(args: Array[String]): Unit = {
    var a=Array(2, 5, 3, 4, 3, 9, 3, 2, 5, 4, 1, 3, 22, 7, 2, -5, 8, 4)
    println(a.mkString(","))
    shellSort(a)
    println(a.mkString(","))
  }
}


  

You may also check:How to resolve the algorithm 15 puzzle game step by step in the REXX programming language
You may also check:How to resolve the algorithm Unicode variable names step by step in the Déjà Vu programming language
You may also check:How to resolve the algorithm Anagrams step by step in the Yabasic programming language
You may also check:How to resolve the algorithm Tokenize a string with escaping step by step in the CLU programming language
You may also check:How to resolve the algorithm Command-line arguments step by step in the AWK programming language