Sorting algorithms/Gnome sort: Difference between revisions

Content added Content deleted
(add task to aarch64 assembly raspberry pi)
(→‎{{header|R}}: Used a cool R trick, added more outputs, and tried to follow pseudo-code more closely.)
Line 2,685: Line 2,685:
>>></lang>
>>></lang>


=={{header|R}}==
=={{header|R}}==
===Starting from 1===
<lang r>gnomesort <- function(x)
<lang r>gnomesort <- function(x)
{
{
Line 2,712: Line 2,713:
}
}
gnomesort(c(4, 65, 2, -31, 0, 99, 83, 782, 1)) # -31 0 1 2 4 65 83 99 782</lang>
gnomesort(c(4, 65, 2, -31, 0, 99, 83, 782, 1)) # -31 0 1 2 4 65 83 99 782</lang>

===Starting from 2===
The previously solution misses out on a cool R trick for swapping items.

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.
<lang r>gnomeSort<-function(a)
{
i<-2
j<-3
while(i<=length(a))
{
if(a[i-1]<=a[i])
{
i<-j
j<-j+1
}
else
{
a[c(i-1,i)]<-a[c(i,i-1)]#The cool trick mentioned above.
i<-i-1
if(i==1)
{
i<-j
j<-j+1
}
}
}
a
}
#Examples taken from the Haxe solution.
#Note that R can use <= to compare strings
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")</lang>

{{out}}
<pre>> gnomeSort(ints)
[1] -19 -1 0 1 2 4 5 5 10 23
> gnomeSort(numerics)
[1] -9.5 -5.7 -4.1 -3.2 0.0 1.0 3.5 5.2 7.3 10.8
> gnomeSort(strings)
[1] "all" "are" "be" "created" "equal" "hold" "men"
[8] "self-evident" "that" "these" "to" "truths" "We"</pre>


=={{header|Racket}}==
=={{header|Racket}}==