Jump to content

Sorting algorithms/Cocktail sort: Difference between revisions

→‎{{header|R}}: Used a cool R trick and tried to follow pseudo-code more closely. Also added more outputs.
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:
 
=={{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 Rr>cocktailsort cocktailSort<- function(xA)
{
repeat
lenx <- length(x)
repeat{
swapped <- TRUEFALSE
{
for(i in swapped <1:(length(A)- FALSE1))
{
for(i in 1:(lenx-1))
xif(A[i] <- x>A[i+1])
{
if(xA[c(i,i+1)] > x<-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
for(i in (lenxlength(A)-1):1)
{
xif(A[i] <- x>A[i+1])
{
if(xA[c(i,i+1)] > x<-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}}==
331

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.