Sorting algorithms/Gnome sort: Difference between revisions

m
syntax highlighting fixup automation
No edit summary
m (syntax highlighting fixup automation)
Line 34:
{{trans|Python}}
 
<langsyntaxhighlight lang="11l">F gnomesort(&a)
V i = 1
V j = 2
Line 49:
R a
 
print(gnomesort(&[3, 4, 2, 5, 1, 6]))</langsyntaxhighlight>
 
{{out}}
Line 57:
 
=={{header|360 Assembly}}==
<langsyntaxhighlight lang="360asm">* Gnome sort - Array base 0 - 15/04/2020
GNOME CSECT
USING GNOME,R13 base register
Line 112:
PG DC CL125' ' buffer
REGEQU
END GNOME</langsyntaxhighlight>
{{out}}
<pre>
Line 120:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
<lang AArch64 Assembly>
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program gnomeSort64.s */
Line 286:
.include "../includeARM64.inc"
 
</syntaxhighlight>
</lang>
 
=={{header|Action!}}==
<langsyntaxhighlight Actionlang="action!">PROC PrintArray(INT ARRAY a INT size)
INT i
 
Line 342:
Test(c,8)
Test(d,12)
RETURN</langsyntaxhighlight>
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Gnome_sort.png Screenshot from Atari 8-bit computer]
Line 368:
 
=={{header|ActionScript}}==
<langsyntaxhighlight ActionScriptlang="actionscript">function gnomeSort(array:Array)
{
var pos:uint = 0;
Line 384:
}
return array;
}</langsyntaxhighlight>
 
=={{header|Ada}}==
This example is a generic procedure for constrained array types.
<langsyntaxhighlight Adalang="ada">generic
type Element_Type is private;
type Index is (<>);
type Collection is array(Index) of Element_Type;
with function "<=" (Left, Right : Element_Type) return Boolean is <>;
procedure Gnome_Sort(Item : in out Collection);</langsyntaxhighlight>
 
<langsyntaxhighlight Adalang="ada">procedure Gnome_Sort(Item : in out Collection) is
procedure Swap(Left, Right : in out Element_Type) is
Temp : Element_Type := Left;
Line 419:
end if;
end loop;
end Gnome_Sort;</langsyntaxhighlight>
Usage example:
<langsyntaxhighlight Adalang="ada">with Gnome_Sort;
with Ada.Text_Io; use Ada.Text_Io;
 
Line 439:
end loop;
New_Line;
end Gnome_Sort_Test;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Line 447:
 
{{works with|ELLA ALGOL 68|Any (with appropriate job cards AND formatted transput statements removed) - tested with release 1.8.8d.fc9.i386}}
<langsyntaxhighlight lang="algol68">MODE SORTSTRUCT = CHAR;
 
PROC inplace gnome sort = (REF[]SORTSTRUCT list)REF[]SORTSTRUCT:
Line 468:
 
[]SORTSTRUCT char array data = "big fjords vex quick waltz nymph";
print((gnome sort(char array data), new line))</langsyntaxhighlight>
Output:
<pre>
Line 475:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<syntaxhighlight lang="arm assembly">
<lang ARM Assembly>
/* ARM assembly Raspberry PI */
/* program gnomeSort.s */
Line 632:
.include "../affichage.inc"
 
</syntaxhighlight>
</lang>
 
=={{header|Arturo}}==
 
<langsyntaxhighlight lang="rebol">gnomeSort: function [items][
i: 1
j: 2
Line 660:
]
 
print gnomeSort [3 1 2 8 5 7 9 4 6]</langsyntaxhighlight>
 
{{out}}
Line 668:
=={{header|AutoHotkey}}==
contributed by Laszlo on the ahk [http://www.autohotkey.com/forum/post-276379.html#276379 forum]
<langsyntaxhighlight AutoHotkeylang="autohotkey">MsgBox % GnomeSort("")
MsgBox % GnomeSort("xxx")
MsgBox % GnomeSort("3,2,1")
Line 689:
sorted .= "," . a%A_Index%
Return SubStr(sorted,2) ; drop leading comma
}</langsyntaxhighlight>
 
=={{header|AWK}}==
Line 697:
This version includes the mark/resume optimization. It remembers where it was before backing up so that once an item is backed up to its proper place the process resumes from where it was before backing up.
 
<langsyntaxhighlight lang="awk">#!/usr/bin/awk -f
 
BEGIN {
Line 735:
print ""
}
</syntaxhighlight>
</lang>
 
Example output:
Line 745:
 
{{trans|C}}
<langsyntaxhighlight lang="qbasic">dim a(0 to n-1) as integer
'...more code...
sort:
Line 763:
end if
end if
wend</langsyntaxhighlight>
 
=={{header|Batch File}}==
{{works with|Windows NT}}
 
<langsyntaxhighlight lang="dos">@ECHO OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
:: GnomeSort.cmd in WinNT Batch using pseudo array.
Line 827:
 
ENDLOCAL
EXIT /B 0</langsyntaxhighlight>
 
=={{header|BBC BASIC}}==
<langsyntaxhighlight BBCBASIClang="bbcbasic">DEF PROC_GnomeSort1(Size%)
I%=2
J%=2
Line 846:
ENDIF
UNTIL I%>Size%
ENDPROC</langsyntaxhighlight>
 
=={{header|BCPL}}==
<langsyntaxhighlight lang="bcpl">get "libhdr"
 
let gnomesort(A, len) be
Line 881:
gnomesort(array, length)
writes("Output: ") ; writearray(array, length) ; wrch('*N')
$)</langsyntaxhighlight>
{{out}}
<pre>Input: 52 -5 -20 199 65 -3 190 25 9999 -5342
Line 889:
 
This algorithm sorts in place modifying the passed ''array'' (of <code>n</code> integer numbers).
<langsyntaxhighlight lang="c">void gnome_sort(int *a, int n)
{
int i=1, j=2, t;
Line 901:
}
# undef swap
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
 
<langsyntaxhighlight lang="csharp">
public static void gnomeSort(int[] anArray)
{
Line 933:
}
}
</syntaxhighlight>
</lang>
 
=={{header|C++}}==
Uses C++11. Compile with
g++ -std=c++11 gnome.cpp
<langsyntaxhighlight lang="cpp">#include <algorithm>
#include <iterator>
#include <iostream>
Line 967:
copy(std::begin(a), std::end(a), std::ostream_iterator<int>(std::cout, " "));
std::cout << "\n";
}</langsyntaxhighlight>
Output:
<pre>
Line 975:
=={{header|Clojure}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="clojure">(defn gnomesort
([c] (gnomesort c <))
([c pred]
Line 986:
(recur (concat x (list y1)) ys)))))))
 
(println (gnomesort [3 1 4 1 5 9 2 6 5]))</langsyntaxhighlight>
 
=={{header|COBOL}}==
Procedure division stuff only.
<langsyntaxhighlight COBOLlang="cobol"> C-SORT SECTION.
C-000.
DISPLAY "SORT STARTING".
Line 1,019:
 
E-999.
EXIT.</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
<langsyntaxhighlight lang="lisp">(defun gnome-sort (array predicate &aux (length (length array)))
(do ((position (min 1 length)))
((eql length position) array)
Line 1,034:
(aref array (1- position)))
(decf position))
(t (incf position)))))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio, std.algorithm;
 
void gnomeSort(T)(T arr) {
Line 1,060:
gnomeSort(a);
writeln(a);
}</langsyntaxhighlight>
 
=={{header|Delphi}}==
Line 1,066:
 
Static array is an arbitrary-based array of fixed length
<langsyntaxhighlight Delphilang="delphi">program TestGnomeSort;
 
{$APPTYPE CONSOLE}
Line 1,124:
Writeln;
Readln;
end.</langsyntaxhighlight>
Output:
<pre>
Line 1,132:
 
=={{header|DWScript}}==
<langsyntaxhighlight lang="delphi">procedure GnomeSort(a : array of Integer);
var
i, j : Integer;
Line 1,169:
Print(Format('%3d ', [a[i]]));
PrintLn('}');
</syntaxhighlight>
</lang>
Ouput :
<pre>
Line 1,178:
=={{header|E}}==
 
<langsyntaxhighlight lang="e">def gnomeSort(array) {
var size := array.size()
var i := 1
Line 1,197:
}
}
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="e">? def a := [7,9,4,2,1,3,6,5,0,8].diverge()
# value: [7, 9, 4, 2, 1, 3, 6, 5, 0, 8].diverge()
 
? gnomeSort(a)
? a
# value: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9].diverge()</langsyntaxhighlight>
 
=={{header|Eiffel}}==
 
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
GNOME_SORT [G -> COMPARABLE]
Line 1,273:
end
 
</syntaxhighlight>
</lang>
Test:
<syntaxhighlight lang="eiffel">
<lang Eiffel>
class
APPLICATION
Line 1,310:
end
 
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 1,321:
=={{header|Elena}}==
ELENA 5.0 :
<langsyntaxhighlight lang="elena">import extensions;
import system'routines;
Line 1,361:
console.printLine("before:", list.asEnumerable());
console.printLine("after :", list.gnomeSort().asEnumerable())
}</langsyntaxhighlight>
{{out}}
<pre>
Line 1,370:
=={{header|Elixir}}==
{{trans|Erlang}}
<langsyntaxhighlight lang="elixir">defmodule Sort do
def gnome_sort([]), do: []
def gnome_sort([h|t]), do: gnome_sort([h], t)
Line 1,379:
end
 
IO.inspect Sort.gnome_sort([8,3,9,1,3,2,6])</langsyntaxhighlight>
 
{{out}}
Line 1,388:
=={{header|Erlang}}==
 
<langsyntaxhighlight Erlanglang="erlang">-module(gnome_sort).
-export([gnome/1]).
 
Line 1,396:
gnome(P, [Next|N]) ->
gnome([Next|P], N).
gnome([H|T]) -> gnome([H], T).</langsyntaxhighlight>
<langsyntaxhighlight Erlanglang="erlang">Eshell V5.7.3 (abort with ^G)
1> c(gnome_sort).
{ok,gnome_sort}
2> gnome_sort:gnome([8,3,9,1,3,2,6]).
[1,2,3,3,6,8,9]
3> </langsyntaxhighlight>
 
=={{header|Euphoria}}==
<langsyntaxhighlight lang="euphoria">function gnomeSort(sequence s)
integer i,j
object temp
Line 1,426:
end while
return s
end function</langsyntaxhighlight>
 
=={{header|F Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">let inline gnomeSort (a: _ []) =
let rec loop i j =
if i < a.Length then
Line 1,437:
a.[i] <- t
if i=1 then loop j (j+1) else loop (i-1) j
loop 1 2</langsyntaxhighlight>
 
=={{header|Factor}}==
Line 1,473:
=={{header|Fantom}}==
 
<langsyntaxhighlight lang="fantom">
class Main
{
Line 1,508:
}
}
</syntaxhighlight>
</lang>
 
Output:
Line 1,516:
 
=={{header|Forth}}==
<langsyntaxhighlight lang="forth">defer precedes
defer exchange
 
Line 1,539:
: .array 10 0 do example i cells + ? loop cr ;
 
.array example 10 gnomesort .array</langsyntaxhighlight>
A slightly optimized version is presented below, where Gnome sort keeps track of its previous position. This reduces the number of iterations significantly.
<langsyntaxhighlight lang="forth">: gnomesort+ ( a n)
swap >r 2 tuck 1- ( c2 n c1)
begin ( c2 n c1)
Line 1,551:
else drop >r dup 1+ swap r> swap then
repeat drop drop drop r> drop
; ( --)</langsyntaxhighlight>
 
=={{header|Fortran}}==
{{works with|Fortran|90 and later}}
<langsyntaxhighlight lang="fortran">program example
implicit none
Line 1,650:
!
end program example</langsyntaxhighlight>
 
=={{header|FreeBASIC}}==
Used the task pseudo code as a base
<langsyntaxhighlight lang="freebasic">' version 21-10-2016
' compile with: fbc -s console
' for boundry checks on array's compile with: fbc -s console -exx
Line 1,704:
Print : Print "hit any key to end program"
Sleep
End</langsyntaxhighlight>
{{out}}
<pre>unsort 4 -5 5 1 -3 -1 -2 -6 0 7 -4 6 2 -7 3
Line 1,711:
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=d91a871bd9f43cd9644c89baa3ee861a Click this link to run this code]'''
<langsyntaxhighlight lang="gambas">Public Sub Main()
Dim siCount As Short
Dim siCounti As Short = 1
Line 1,749:
Return
 
End</langsyntaxhighlight>
Output:
<pre>
Line 1,757:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import "fmt"
Line 1,780:
j++
}
}</langsyntaxhighlight>
 
More generic version that sorts anything that implements <code>sort.Interface</code>:
<langsyntaxhighlight lang="go">package main
 
import (
Line 1,809:
j++
}
}</langsyntaxhighlight>
 
=={{header|Groovy}}==
Solution:
<langsyntaxhighlight lang="groovy">def makeSwap = { a, i, j = i+1 -> print "."; a[[j,i]] = a[[i,j]] }
 
def checkSwap = { list, i, j = i+1 -> [(list[i] > list[j])].find{ it }.each { makeSwap(list, i, j) } }
Line 1,824:
}
input
}</langsyntaxhighlight>
 
Test:
<langsyntaxhighlight lang="groovy">println (gnomeSort([23,76,99,58,97,57,35,89,51,38,95,92,24,46,31,24,14,12,57,78,4]))
println (gnomeSort([88,18,31,44,4,0,8,81,14,78,20,76,84,33,73,75,82,5,62,70,12,7,1]))</langsyntaxhighlight>
 
Output:
Line 1,835:
 
=={{header|Haskell}}==
<langsyntaxhighlight lang="haskell">gnomeSort [] = []
gnomeSort (x:xs) = gs [x] xs
where
Line 1,843:
gs [] (y:ys) = gs [y] ys
gs xs [] = reverse xs
-- keeping the first argument of gs in reverse order avoids the deterioration into cubic behaviour </langsyntaxhighlight>
 
=={{header|Haxe}}==
<langsyntaxhighlight lang="haxe">class GnomeSort {
@:generic
public static function sort<T>(arr:Array<T>) {
Line 1,884:
Sys.println('Sorted Strings: ' + stringArray);
}
}</langsyntaxhighlight>
 
{{out}}
Line 1,897:
 
=={{header|Icon}} and {{header|Unicon}}==
<langsyntaxhighlight Iconlang="icon">procedure main() #: demonstrate various ways to sort a list and string
demosort(gnomesort,[3, 14, 1, 5, 9, 2, 6, 3],"qwerty")
end
Line 1,915:
}
return X
end</langsyntaxhighlight>
 
Note: This example relies on [[Sorting_algorithms/Bubble_sort#Icon| the supporting procedures 'sortop', and 'demosort' in Bubble Sort]]. The full demosort exercises the named sort of a list with op = "numeric", "string", ">>" (lexically gt, descending),">" (numerically gt, descending), a custom comparator, and also a string.
Line 1,928:
=={{header|Io}}==
Naive version:
<langsyntaxhighlight lang="io">List do(
gnomeSortInPlace := method(
idx := 1
Line 1,943:
 
lst := list(5, -1, -4, 2, 9)
lst gnomeSortInPlace println # ==> list(-4, -1, 2, 5, 9)</langsyntaxhighlight>
 
Optimized version, storing the position before traversing back towards the begining of the list ([[wp:Gnome_sort#Optimization|Wikipedia]])
<langsyntaxhighlight lang="io">List do(
gnomeSortInPlace := method(
idx1 := 1
Line 1,964:
 
lst := list(5, -1, -4, 2, 9)
lst gnomeSortInPlace println # ==> list(-4, -1, 2, 5, 9)</langsyntaxhighlight>
 
=={{header|IS-BASIC}}==
<syntaxhighlight lang="is-basic">
<lang IS-BASIC>
100 PROGRAM "GnomeSrt.bas"
110 RANDOMIZE
Line 1,997:
370 END IF
380 LOOP
390 END DEF</langsyntaxhighlight>
 
=={{header|J}}==
{{eff note|J|/:~}}
<langsyntaxhighlight Jlang="j">position=: 0 {.@I.@, [
swap=: ] A.~ *@position * #@[ !@- <:@position
gnome=: swap~ 2 >/\ ]
gnomes=: gnome^:_</langsyntaxhighlight>
 
Note 1: this implementation of swap is actually rather silly, and will not work on long lists. A better implementation would be:<langsyntaxhighlight Jlang="j">swap=: position (] {~ _1 0 + [)`(0 _1 + [)`]}^:(*@[) ]</langsyntaxhighlight>
 
Note 2: this implementation only works for domains where > is defined (in J, "greater than" only works on numbers). To work around this issue, you could define:<langsyntaxhighlight Jlang="j">gt=: -.@(-: /:~)@,&<
gnome=: swap~ 2 gt/\ ]</langsyntaxhighlight>
 
Note 3: this implementation does not return intermediate results. If you want them, you could use<langsyntaxhighlight Jlang="j">gnomeps=: gnome^:a:</langsyntaxhighlight>
 
Note 4: gnomeps just shows intermediate results and does not show the gnome's position. You can extract the gnome's position using an expression such as<syntaxhighlight lang J="j">2 ~:/\ gnomeps</langsyntaxhighlight>.
 
=={{header|Java}}==
{{trans|C}}
<langsyntaxhighlight lang="java">public static void gnomeSort(int[] a)
{
int i=1;
Line 2,032:
}
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
<langsyntaxhighlight lang="javascript">function gnomeSort(a) {
function moveBack(i) {
for( ; i > 0 && a[i-1] > a[i]; i--) {
Line 2,047:
}
return a;
}</langsyntaxhighlight>
 
=={{header|jq}}==
Line 2,053:
This implementation adheres to the specification.
The array to be sorted, however, can be any JSON array.
<langsyntaxhighlight 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;
Line 2,076:
end
end )
| .[2];</langsyntaxhighlight>
'''Example''':
<langsyntaxhighlight lang="jq">[(2|sqrt), [1], null, 1, 0.5, 2, 1, -3, {"a": "A"}] | gnomeSort</langsyntaxhighlight>
{{Out}}
<langsyntaxhighlight lang="sh">$ jq -M -n -f Gnome_sort.jq
[
null,
Line 2,095:
"a": "A"
}
]</langsyntaxhighlight>
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<langsyntaxhighlight lang="julia">function gnomesort!(arr::Vector)
i, j = 1, 2
while i < length(arr)
Line 2,119:
 
v = rand(-10:10, 10)
println("# unordered: $v\n -> ordered: ", gnomesort!(v))</langsyntaxhighlight>
 
{{out}}
Line 2,126:
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.1.0
 
fun <T: Comparable<T>> gnomeSort(a: Array<T>, ascending: Boolean = true) {
Line 2,150:
gnomeSort(array, false)
println("Sorted (desc) : ${array.asList()}")
}</langsyntaxhighlight>
 
{{out}}
Line 2,161:
=={{header|Lua}}==
Keep in mind that Lua arrays initial index is 1.
<langsyntaxhighlight lang="lua">function gnomeSort(a)
local i, j = 2, 3
 
Line 2,177:
end
end
end</langsyntaxhighlight>
Example:
<langsyntaxhighlight lang="lua">list = { 5, 6, 1, 2, 9, 14, 2, 15, 6, 7, 8, 97 }
gnomeSort(list)
for i, j in pairs(list) do
print(j)
end</langsyntaxhighlight>
 
=={{header|Maple}}==
<langsyntaxhighlight Maplelang="maple">arr := Array([17,3,72,0,36,2,3,8,40,0]):
len := numelems(arr):
i := 2:
Line 2,199:
end if:
end do:
arr;</langsyntaxhighlight>
{{Out|Output}}
<pre>[0,0,2,3,3,8,17,36,40,72]</pre>
 
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<langsyntaxhighlight Mathematicalang="mathematica">gnomeSort[list_]:=Module[{i=2,j=3},
While[ i<=Length[[list]],
If[ list[[i-1]]<=list[[i]],
Line 2,210:
list[[i-1;;i]]=list[[i;;i-1]];i--;];
If[i==1,i=j;j++;]
]]</langsyntaxhighlight>
 
=={{header|MATLAB}} / {{header|Octave}}==
<langsyntaxhighlight MATLABlang="matlab">function list = gnomeSort(list)
 
i = 2;
Line 2,233:
end %while
end %gnomeSort</langsyntaxhighlight>
 
Sample Usage:
<langsyntaxhighlight MATLABlang="matlab">>> gnomeSort([4 3 1 5 6 2])
 
ans =
 
1 2 3 4 5 6</langsyntaxhighlight>
 
=={{header|MAXScript}}==
<langsyntaxhighlight MAXScriptlang="maxscript">fn gnomeSort arr =
(
local i = 2
Line 2,266:
)
return arr
)</langsyntaxhighlight>
Output:
<syntaxhighlight lang="maxscript">
<lang MAXScript>
a = for i in 1 to 10 collect random 1 20
#(20, 10, 16, 2, 19, 12, 11, 3, 5, 16)
gnomesort a
#(2, 3, 5, 10, 11, 12, 16, 16, 19, 20)
</syntaxhighlight>
</lang>
 
=={{header|Metafont}}==
<langsyntaxhighlight lang="metafont">def gnomesort(suffix v)(expr n) =
begingroup save i, j, t;
i := 1; j := 2;
Line 2,290:
fi
endfor
endgroup enddef;</langsyntaxhighlight>
 
<langsyntaxhighlight lang="metafont">numeric a[];
for i = 0 upto 9: a[i] := uniformdeviate(40); message decimal a[i]; endfor
message char10;
Line 2,298:
gnomesort(a, 10);
for i = 0 upto 9: message decimal a[i]; endfor
end</langsyntaxhighlight>
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref savelog symbols binary
 
Line 2,351:
 
return ra
</syntaxhighlight>
</lang>
;Output
<pre>
Line 2,359:
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">proc gnomeSort[T](a: var openarray[T]) =
var
n = a.len
Line 2,374:
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
gnomeSort a
echo a</langsyntaxhighlight>
Output:
<pre>@[-31, 0, 2, 2, 4, 65, 83, 99, 782]</pre>
Line 2,380:
=={{header|Objeck}}==
{{trans|C}}
<langsyntaxhighlight lang="objeck">
function : GnomeSort(a : Int[]) {
i := 1;
Line 2,402:
};
}
</syntaxhighlight>
</lang>
 
=={{header|OCaml}}==
from the toplevel:
<langsyntaxhighlight lang="ocaml"># let gnome_sort a =
let i = ref 1
and j = ref 2 in
Line 2,433:
 
# a ;;
- : int array = [|0; 1; 2; 3; 4; 5; 6; 7; 8; 9|]</langsyntaxhighlight>
 
=={{header|Octave}}==
<langsyntaxhighlight lang="octave">function s = gnomesort(v)
i = 2; j = 3;
while ( i <= length(v) )
Line 2,454:
endwhile
s = v;
endfunction</langsyntaxhighlight>
 
<langsyntaxhighlight lang="octave">v = [7, 9, 4, 2, 1, 3, 6, 5, 0, 8];
disp(gnomesort(v));</langsyntaxhighlight>
 
=={{header|ooRexx}}==
===version 1===
{{Trans|NetRexx}}
<langsyntaxhighlight ooRexxlang="oorexx">/* Rexx */
 
call demo
Line 2,557:
self~put(item, ix)
return
</syntaxhighlight>
</lang>
'''Output:
<pre>
Line 2,585:
===version 2===
{{trans|REXX}}
<langsyntaxhighlight lang="oorexx">/* REXX ---------------------------------------------------------------
* 28.06.2014 Walter Pachl
* 30.06.2014 corrected in sync with REXX version 2
Line 2,624:
Say 'element' right(i,2) x[i]
End
Return</langsyntaxhighlight>
'''output'''
Similar to REXX version 2
Line 2,630:
=={{header|Oz}}==
{{trans|Haskell}}
<langsyntaxhighlight lang="oz">declare
fun {GnomeSort Xs}
case Xs of nil then nil
Line 2,646:
end
in
{Show {GnomeSort [3 1 4 1 5 9 2 6 5]}}</langsyntaxhighlight>
 
=={{header|PARI/GP}}==
<langsyntaxhighlight lang="parigp">gnomeSort(v)={
my(i=2,j=3,n=#v,t);
while(i<=n,
Line 2,663:
);
v
};</langsyntaxhighlight>
 
=={{header|Pascal}}==
<langsyntaxhighlight lang="pascal">procedure gnomesort(var arr : Array of Integer; size : Integer);
var
i, j, t : Integer;
Line 2,689:
end
end;
end;</langsyntaxhighlight>
 
=={{header|Perl}}==
<langsyntaxhighlight lang="perl">use strict;
 
sub gnome_sort
Line 2,715:
}
return @a;
}</langsyntaxhighlight>
 
<langsyntaxhighlight lang="perl">my @arr = ( 10, 9, 8, 5, 2, 1, 1, 0, 50, -2 );
print "$_\n" foreach gnome_sort( @arr );</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="phix">(phixonline)-->
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
Line 2,746:
<span style="color: #0000FF;">?</span><span style="color: #000000;">gnomeSort</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">shuffle</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">tagset</span><span style="color: #0000FF;">(</span><span style="color: #000000;">10</span><span style="color: #0000FF;">)))</span>
<!--</langsyntaxhighlight>-->
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php">function gnomeSort($arr){
$i = 1;
$j = 2;
Line 2,768:
}
$arr = array(3,1,6,2,9,4,7,8,5);
echo implode(',',gnomeSort($arr));</langsyntaxhighlight>
<pre>1,2,3,4,5,6,7,8,9</pre>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="picolisp">(de gnomeSort (Lst)
(let J (cdr Lst)
(for (I Lst (cdr I))
Line 2,781:
(setq I J J (cdr J))
(setq I (prior I Lst)) ) ) ) )
Lst )</langsyntaxhighlight>
 
=={{header|PL/I}}==
<langsyntaxhighlight PLlang="pl/Ii">SORT: PROCEDURE OPTIONS (MAIN);
DECLARE A(0:9) FIXED STATIC INITIAL (5, 2, 7, 1, 9, 8, 6, 3, 4, 0);
 
Line 2,811:
END GNOME_SORT;
 
END SORT;</langsyntaxhighlight>
Results:
<pre>
Line 2,821:
The [[#BASIC|BASIC]] example will work as-is if the array is declared in the same function as the sort. This example doesn't require that, but forces you to know your data type beforehand.
 
<langsyntaxhighlight lang="powerbasic">SUB gnomeSort (a() AS LONG)
DIM i AS LONG, j AS LONG
i = 1
Line 2,854:
NEXT
CLOSE 1
END FUNCTION</langsyntaxhighlight>
 
Sample output:
Line 2,861:
 
=={{header|PowerShell}}==
<syntaxhighlight lang="powershell">
<lang PowerShell>
function gnomesort($a) {
$size, $i, $j = $a.Count, 1, 2
Line 2,882:
$array = @(60, 21, 19, 36, 63, 8, 100, 80, 3, 87, 11)
"$(gnomesort $array)"
</syntaxhighlight>
</lang>
<b>Output:</b>
<pre>
Line 2,889:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="purebasic">Procedure GnomeSort(Array a(1))
Protected Size = ArraySize(a()) + 1
Protected i = 1, j = 2
Line 2,907:
EndIf
Wend
EndProcedure</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">>>> def gnomesort(a):
i,j,size = 1,2,len(a)
while i < size:
Line 2,924:
>>> gnomesort([3,4,2,5,1,6])
[1, 2, 3, 4, 5, 6]
>>></langsyntaxhighlight>
 
=={{header|Quackery}}==
 
<langsyntaxhighlight Quackerylang="quackery">[ dup size times
[ i^ 0 > if
[ dup i^ 1 - peek
Line 2,936:
swap i^ 1 - poke
-1 step ]
else 2drop ] ] ] is gnomesort ( [ --> [ )</langsyntaxhighlight>
 
=={{header|R}}==
===Starting from 1===
<langsyntaxhighlight lang="rsplus">gnomesort <- function(x)
{
i <- 1
Line 2,965:
x
}
gnomesort(c(4, 65, 2, -31, 0, 99, 83, 782, 1)) # -31 0 1 2 4 65 83 99 782</langsyntaxhighlight>
 
===Starting from 2===
Line 2,971:
 
As R is 1-indexed, we need to make some minor adjustments to the given pseudo-code. To give some variety and to remove the previous solution's potentially redundant first run, we have chosen a different adjustment to the previous solution's. We have otherwise aimed to be faithful to the pseudo-code.
<langsyntaxhighlight lang="rsplus">gnomeSort <- function(a)
{
i <- 2
Line 2,999:
ints <- c(1, 10, 2, 5, -1, 5, -19, 4, 23, 0)
numerics <- c(1, -3.2, 5.2, 10.8, -5.7, 7.3, 3.5, 0, -4.1, -9.5)
strings <- c("We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal")</langsyntaxhighlight>
 
{{out}}
Line 3,011:
 
=={{header|Racket}}==
<langsyntaxhighlight lang="racket">
#lang racket
 
Line 3,046:
[else `(,ps ,n ,p . ,ns)]))]))]))
(gnome-sort2 '(3 2 1 4 5 6) <=)
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
Line 3,052:
{{Works with|rakudo|2016.03}}
 
<syntaxhighlight lang="raku" perl6line>sub gnome_sort (@a) {
my ($i, $j) = 1, 2;
while $i < @a {
Line 3,064:
}
}
}</langsyntaxhighlight>
 
my @n = (1..10).roll(20);
Line 3,070:
 
=={{header|Rascal}}==
<langsyntaxhighlight lang="rascal">import List;
 
public list[int] gnomeSort(a){
Line 3,088:
j += 1;}}}
return a;
}</langsyntaxhighlight>
 
An example output:
 
<langsyntaxhighlight lang="rascal">gnomeSort([4, 65, 2, -31, 0, 99, 83, 782, 1])
list[int]: [-31,0,1,2,4,65,83,99,782]</langsyntaxhighlight>
 
=={{header|REXX}}==
===version 1===
This REXX version uses an unity-based array &nbsp; (instead of a zero-based array).
<langsyntaxhighlight lang="rexx">/*REXX program sorts an array using the gnome sort algorithm (elements contain blanks). */
call gen /*generate the @ stemmed array. */
call show 'before sort' /*display the before array elements.*/
Line 3,118:
end /*j*/; return
/*──────────────────────────────────────────────────────────────────────────────────────*/
show: do j=1 for #; say ' element' right(j, w) arg(1)":" @.j; end; return</langsyntaxhighlight>
{{out|output|:}}
 
Line 3,145:
 
===version 2===
<langsyntaxhighlight lang="rexx">/* REXX ---------------------------------------------------------------
* 28.06.2014 Walter Pachl cf ooRexx version 2
* only style changes (reformatting) and adapt for ooRexx compatibility
Line 3,191:
End
Return
</syntaxhighlight>
</lang>
'''output'''
<pre>before sort
Line 3,215:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
aList = [ 5, 6, 1, 2, 9, 14, 15, 7, 8, 97]
gnomeSort(aList)
Line 3,237:
i = j
j = j + 1 ok ok end
</syntaxhighlight>
</lang>
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">class Array
def gnomesort!
i, j = 1, 2
Line 3,259:
ary = [7,6,5,9,8,4,3,1,2,0]
ary.gnomesort!
# => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">fn gnome_sort<T: PartialOrd>(a: &mut [T]) {
let len = a.len();
let mut i: usize = 1;
Line 3,287:
gnome_sort(&mut v);
println!("after: {:?}", v);
}</langsyntaxhighlight>
 
{{out}}
Line 3,296:
 
=={{header|Scala}}==
<langsyntaxhighlight Scalalang="scala">object GnomeSort {
def gnomeSort(a: Array[Int]): Unit = {
var (i, j) = (1, 2)
Line 3,308:
}
}
}</langsyntaxhighlight>
 
=={{header|Scheme}}==
<langsyntaxhighlight lang="scheme">; supply comparison function, which returns true if first and second
; arguments are in order or equal.
(define (gnome-sort-compar in-order input-list)
Line 3,331:
(gnome
(cdr p) ; Prev list shorter by one
(cons next-pot (cons prev-pot (cdr n))))))))))</langsyntaxhighlight>
#;1> (gnome-sort-compar <= '(98 36 2 78 5 81 32 90 73 21 94 28 53 25 10 99))
(2 5 10 21 25 28 32 36 53 73 78 81 90 94 98 99)
 
=={{header|Sidef}}==
<langsyntaxhighlight lang="ruby">class Array {
method gnomesort {
var (i=1, j=2);
Line 3,356:
 
var ary = [7,6,5,9,8,4,3,1,2,0];
say ary.gnomesort;</langsyntaxhighlight>
{{out}}
<pre>[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]</pre>
Line 3,362:
=={{header|Smalltalk}}==
 
<langsyntaxhighlight lang="smalltalk">Smalltalk at: #gnomesort put: nil.
 
"Utility"
Line 3,394:
]
]
].</langsyntaxhighlight>
 
'''Testing'''
 
<langsyntaxhighlight lang="smalltalk">|r o|
r := Random new.
o := OrderedCollection new.
Line 3,406:
gnomesort value: o.
 
1 to: 10 do: [ :i | (o at: i) displayNl ].</langsyntaxhighlight>
 
=={{header|SNOBOL4}}==
Line 3,412:
Implementation of the Gnome sort. Note this is an overengineered approach that performs many checks the real world would need but might obfuscate intent. As such the actual implementation is carefully labelled and the rest can be ignored except as interest dictates.
 
<langsyntaxhighlight lang="snobol4">*** GNOME SORT *****************************************************************
* GNOME(V) -- gnome sort of the numerical vector V.
*** HELPER FUNCTIONS ***********************************************************
Line 3,474:
prototype(v) ',' :S(FRETURN)F(RETURN)
****************************************
GNOME.END</langsyntaxhighlight>
 
The test script looks like this:
<langsyntaxhighlight lang="snobol4">-INCLUDE 'gnome_sort.sno'
 
GNOME.TEST output = 'valid values...'
Line 3,505:
output = 'PASSED!'
 
END</langsyntaxhighlight>
 
=={{header|Swift}}==
<langsyntaxhighlight lang="swift">func gnomeSort<T: Comparable>(_ a: inout [T]) {
var i = 1
var j = 2
Line 3,529:
print("before: \(array)")
gnomeSort(&array)
print(" after: \(array)")</langsyntaxhighlight>
 
{{out}}
Line 3,539:
=={{header|Tcl}}==
{{tcllib|struct::list}}
<langsyntaxhighlight lang="tcl">package require Tcl 8.5
package require struct::list
 
Line 3,562:
}
 
puts [gnomesort {8 6 4 2 1 3 5 7 9}] ;# => 1 2 3 4 5 6 7 8 9</langsyntaxhighlight>
 
=={{header|TI-83 BASIC}}==
Line 3,597:
=={{header|True BASIC}}==
{{trans|IS-BASIC}}
<langsyntaxhighlight lang="qbasic">
RANDOMIZE !RAMDOMZE TIMER en QBASIC
DIM array(-5 TO 12)
Line 3,641:
NEXT i
END SUB
</syntaxhighlight>
</lang>
 
 
=={{header|uBasic/4tH}}==
<syntaxhighlight lang="text">PRINT "Gnome sort:"
n = FUNC (_InitArray)
PROC _ShowArray (n)
Line 3,697:
PRINT
RETURN</langsyntaxhighlight>
 
=={{header|Ursala}}==
Line 3,704:
finding an item out of order, bubble it backwards to its
proper position and resume scanning forward from where it was.
<langsyntaxhighlight Ursalalang="ursala">gnome_sort "p" =
 
@NiX ^=lx -+ # iteration
~&r?\~& @lNXrX ->llx2rhPlrPCTxPrtPX~&lltPlhPrCXPrX ~&ll&& @llPrXh not "p", # backward bubble
->~&rhPlCrtPX ~&r&& ~&lZ!| @bh "p"+- # forward scan</langsyntaxhighlight>
Most of the code is wasted on dull but unavoidable stack manipulations.
Here is a test program using the lexical partial order relation.
<langsyntaxhighlight Ursalalang="ursala">#import std
#cast %s
 
t = gnome_sort(lleq) 'dfijhkwlawfkjnksdjnoqwjefgflkdsgioi'</langsyntaxhighlight>
output:
<pre>
Line 3,721:
 
=={{header|VBA}}==
{{trans|Phix}}<langsyntaxhighlight lang="vb">Private Function gnomeSort(s As Variant) As Variant
Dim i As Integer: i = 1
Dim j As Integer: j = 2
Line 3,745:
Public Sub main()
Debug.Print Join(gnomeSort([{5, 3, 1, 7, 4, 1, 1, 20}]), ", ")
End Sub</langsyntaxhighlight>{{out}}
<pre>1, 1, 1, 3, 4, 5, 7, 20</pre>
 
=={{header|VBScript}}==
====Implementation====
<langsyntaxhighlight lang="vb">function gnomeSort( a )
dim i
dim j
Line 3,776:
x = y
y = temp
end sub</langsyntaxhighlight>
====Invocation====
<langsyntaxhighlight lang="vb">dim a
dim b
 
Line 3,799:
a = array( now(), now()-1,now()+2)
b = gnomeSort( a )
wscript.echo join(a, ", ")</langsyntaxhighlight>
 
====Output====
<langsyntaxhighlight VBScriptlang="vbscript">aardvark, ampicillin, gogodala, wolverhampton, zanzibar, zulu
23, 89, 234, 345, 456, 456, 547, 567, 567, 568, 649, 2345, 5769
True, True, True, True, False, False, False, False
-45.99, -3, 1, 2, 2, 4, 67789
2/02/2010 10:19:51 AM, 3/02/2010 10:19:51 AM, 5/02/2010 10:19:51 AM</langsyntaxhighlight>
Note: All data in VBScript is of type Variant. Thus the code can sort many different types of data without code modification.
 
=={{header|Vlang}}==
{{trans|go}}
<langsyntaxhighlight lang="vlang">fn main() {
mut a := [170, 45, 75, -90, -802, 24, 2, 66]
println("before: $a")
Line 3,830:
j++
}
}</langsyntaxhighlight>
{{out}}
<pre>before: [170, 45, 75, -90, -802, 24, 2, 66]
Line 3,837:
 
=={{header|Wren}}==
<langsyntaxhighlight lang="ecmascript">var gnomeSort = Fn.new { |a, asc|
var size = a.count
var i = 1
Line 3,869:
System.print()
}
}</langsyntaxhighlight>
 
{{out}}
Line 3,891:
 
=={{header|XPL0}}==
<langsyntaxhighlight XPL0lang="xpl0">code ChOut=8, IntOut=11;
 
proc GnomeSort(A(0..Size-1)); \Sort array A
Line 3,918:
GnomeSort(A, 10);
for I:= 0 to 10-1 do [IntOut(0, A(I)); ChOut(0, ^ )];
]</langsyntaxhighlight>
 
{{out}}
Line 3,926:
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">fcn gnomeSort(a){
i,j,size := 1,2,a.len();
while(i < size){
Line 3,938:
}//while
a
}</langsyntaxhighlight>
<langsyntaxhighlight lang="zkl">gnomeSort("This is a test".split("")).println();</langsyntaxhighlight>
{{out}}
<pre>L(" "," "," ","T","a","e","h","i","i","s","s","s","t","t")</pre>
10,327

edits