How to resolve the algorithm Sorting algorithms/Gnome sort step by step in the Smalltalk programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Sorting algorithms/Gnome sort step by step in the Smalltalk programming language

Table of Contents

Problem Statement

Gnome sort is a sorting algorithm which is similar to Insertion sort, except that moving an element to its proper place is accomplished by a series of swaps, as in Bubble Sort. The pseudocode for the algorithm is:

Implement the Gnome sort in your language to sort an array (or list) of numbers.

Let's start with the solution:

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

Source code in the smalltalk programming language

Smalltalk at: #gnomesort put: nil.

"Utility"
OrderedCollection extend [
  swap: a with: b [ |t|
      t := self at: a.
      self at: a put: b.
      self at: b put: t
  ]
].

"Gnome sort as block closure"
gnomesort := [ :c |
  |i j|
  i := 2. j := 3.
  [ i <= (c size) ]
    whileTrue: [
       (c at: (i-1)) <= (c at: i)
          ifTrue: [
             i := j copy.
             j := j + 1.
          ]
          ifFalse: [
             c swap: (i-1) with: i.
             i := i - 1.
             i == 1
               ifTrue: [
                  i := j copy.
                  j := j + 1
               ]
          ]
    ]
].


|r o|
r := Random new.
o := OrderedCollection new.

1 to: 10 do: [ :i | o add: (r between: 0 and: 50) ].

gnomesort value: o.

1 to: 10 do: [ :i | (o at: i) displayNl ].


  

You may also check:How to resolve the algorithm Equal prime and composite sums step by step in the Raku programming language
You may also check:How to resolve the algorithm Amicable pairs step by step in the Haskell programming language
You may also check:How to resolve the algorithm 100 doors step by step in the Raku programming language
You may also check:How to resolve the algorithm Color quantization step by step in the D programming language
You may also check:How to resolve the algorithm Rosetta Code/Rank languages by number of users step by step in the REXX programming language