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

Published on 12 May 2024 09:40 PM
#Jq

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

Source code in the jq programming language

# As soon as "condition" is true, then emit . and stop:
def do_until(condition; next):
  def u: if condition then . else (next|u) end;
  u;

# input: an array
def gnomeSort:
  def swap(i;j): .[i] as $x | .[i]=.[j] | .[j]=$x;

  length as $length
  # state: [i, j, ary]
  | [1, 2, .] 
  | do_until( .[0] >= $length;
              .[0] as $i | .[1] as $j
              | .[2]
              # for descending sort, use >= for comparison
              | if .[$i-1] <= .[$i] then [$j, $j + 1, .]
                else swap( $i-1; $i)
                | ($i - 1) as $i
                | if $i == 0 then [$j, $j + 1, .]
                  else [$i, $j, .]
                  end
                end )
  | .[2];

[(2|sqrt), [1], null, 1, 0.5, 2, 1, -3, {"a": "A"}] | gnomeSort

$ jq -M -n -f Gnome_sort.jq
[
  null,
  -3,
  0.5,
  1,
  1,
  1.4142135623730951,
  2,
  [
    1
  ],
  {
    "a": "A"
  }
]


  

You may also check:How to resolve the algorithm Generate Chess960 starting position step by step in the Julia programming language
You may also check:How to resolve the algorithm Population count step by step in the AutoHotkey programming language
You may also check:How to resolve the algorithm Loops/While step by step in the TorqueScript programming language
You may also check:How to resolve the algorithm Loops/For step by step in the Asymptote programming language
You may also check:How to resolve the algorithm Simple windowed application step by step in the Gastona programming language