Sorting algorithms/Cocktail sort: Difference between revisions

Content added Content deleted
m (→‎{{header|REXX}}: corrected a typo.)
(→‎{{header|R}}: Used a cool R trick and tried to follow pseudo-code more closely. Also added more outputs.)
Line 3,195: Line 3,195:


=={{header|R}}==
=={{header|R}}==
The previously solution missed out on a cool R trick for swapping items. As R is 1-indexed, we have made some minor adjustments to the given pseudo-code. Otherwise, we have aimed to be faithful to it.
<lang R>cocktailsort <- function(x)
<lang r>cocktailSort<-function(A)
{
{
repeat
lenx <- length(x)
repeat
{
swapped<-FALSE
{
swapped <- FALSE
for(i in 1:(length(A)-1))
{
for(i in 1:(lenx-1))
if(A[i]>A[i+1])
{
{
if(x[i] > x[i+1])
A[c(i,i+1)]<-A[c(i+1,i)]#The cool trick mentioned above.
{
swapped<-TRUE
temp <- x[i]
x[i] <- x[i+1]
x[i+1] <- temp
swapped <- TRUE
}
}
}
}
if(!swapped) break
if(!swapped) break
swapped <- FALSE
swapped<-FALSE
for(i in (lenx-1):1)
for(i in (length(A)-1):1)
{
if(A[i]>A[i+1])
{
{
if(x[i] > x[i+1])
A[c(i,i+1)]<-A[c(i+1,i)]
{
swapped<-TRUE
temp <- x[i]
x[i] <- x[i+1]
x[i+1] <- temp
swapped <- TRUE
}
}
}
}
if(!swapped) break
}
if(!swapped) break
x
}
A
}
}
#Examples taken from the Haxe solution.
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}}
print(cocktailsort(c(5, -1, 101, -4, 0, 1, 8, 6, 2, 3)))</lang>
<pre>> cocktailSort(ints)
[1] -19 -1 0 1 2 4 5 5 10 23
> cocktailSort(numerics)
[1] -9.5 -5.7 -4.1 -3.2 0.0 1.0 3.5 5.2 7.3 10.8
> cocktailSort(strings)
[1] "all" "are" "be" "created" "equal" "hold" "men"
[8] "self-evident" "that" "these" "to" "truths" "We"</pre>


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