Sorting algorithms/Cocktail sort: Difference between revisions

Content added Content deleted
m (→‎{{header|R}}: Syntax highlighting.)
m (→‎{{header|R}}: Syntax improvement.)
Line 3,522: Line 3,522:
=={{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.
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 rsplus>cocktailSort<-function(A)
<lang rsplus>cocktailSort <- function(A)
{
{
repeat
repeat
{
{
swapped<-FALSE
swapped <- FALSE
for(i in 1:(length(A)-1))
for(i in seq_len(length(A) - 1))
{
{
if(A[i]>A[i+1])
if(A[i] > A[i + 1])
{
{
A[c(i,i+1)]<-A[c(i+1,i)]#The cool trick mentioned above.
A[c(i, i + 1)] <- A[c(i + 1, i)]#The cool trick mentioned above.
swapped<-TRUE
swapped <- TRUE
}
}
}
}
if(!swapped) break
if(!swapped) break
swapped<-FALSE
swapped <- FALSE
for(i in (length(A)-1):1)
for(i in (length(A)-1):1)
{
{
if(A[i]>A[i+1])
if(A[i] > A[i + 1])
{
{
A[c(i,i+1)]<-A[c(i+1,i)]
A[c(i, i + 1)] <- A[c(i + 1, i)]
swapped<-TRUE
swapped <- TRUE
}
}
}
}
Line 3,550: Line 3,550:
}
}
#Examples taken from the Haxe solution.
#Examples taken from the Haxe solution.
ints<-c(1,10,2,5,-1,5,-19,4,23,0)
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)
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>
strings <- c("We", "hold", "these", "truths", "to", "be", "self-evident", "that", "all", "men", "are", "created", "equal")</lang>


{{out}}
{{out}}