Sorting algorithms/Gnome sort: Difference between revisions

jq
m (→‎version 1: added a comment in the REXX version 1 section header.)
(jq)
Line 1,026:
return a;
}</lang>
 
=={{header|jq}}==
{{works with | jq|1.4}}
This implementation adheres to the specification.
The array to be sorted, however, can be any JSON array.
<lang jq># 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];</lang>
'''Example''':
<lang jq>[(2|sqrt), [1], null, 1, 0.5, 2, 1, -3, {"a": "A"}] | gnomeSort</lang>
{{Out}}
<lang sh>$ jq -M -n -f Gnome_sort.jq
[
null,
-3,
0.5,
1,
1,
1.4142135623730951,
2,
[
1
],
{
"a": "A"
}
]</lang>
 
=={{header|Lua}}==
2,502

edits