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

Published on 12 May 2024 09:40 PM

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

Source code in the haxe programming language

class GnomeSort {
  
  public static function sort<T>(arr:Array<T>) {
    var i = 1;
    var j = 2;
    while (i < arr.length) {
      if (Reflect.compare(arr[i - 1], arr[i]) <= 0) {
        i = j++;
      } else {
        var temp = arr[i];
        arr[i] = arr[i - 1];
        arr[i - 1] = temp;
        if (--i == 0) {
          i = j++;
        }  
      }
    }
  }
}

class Main {
  static function main() {
    var integerArray = [1, 10, 2, 5, -1, 5, -19, 4, 23, 0];
    var floatArray = [1.0, -3.2, 5.2, 10.8, -5.7, 7.3, 
                      3.5, 0.0, -4.1, -9.5];
    var stringArray = ['We', 'hold', 'these', 'truths', 'to', 
                       'be', 'self-evident', 'that', 'all', 
                       'men', 'are', 'created', 'equal'];
    Sys.println('Unsorted Integers: ' + integerArray);
    GnomeSort.sort(integerArray);
    Sys.println('Sorted Integers:   ' + integerArray);
    Sys.println('Unsorted Floats:   ' + floatArray);
    GnomeSort.sort(floatArray);
    Sys.println('Sorted Floats:     ' + floatArray);
    Sys.println('Unsorted Strings:  ' + stringArray);
    GnomeSort.sort(stringArray);
    Sys.println('Sorted Strings:    ' + stringArray);
  }
}


  

You may also check:How to resolve the algorithm Binary digits step by step in the Wren programming language
You may also check:How to resolve the algorithm Archimedean spiral step by step in the AWK programming language
You may also check:How to resolve the algorithm Colorful numbers step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Call a function step by step in the ActionScript programming language
You may also check:How to resolve the algorithm Sierpinski triangle step by step in the FALSE programming language