Sorting algorithms/Bubble sort: Difference between revisions
Content added Content deleted
ReeceGoding (talk | contribs) m (→{{header|R}}: Syntax highlighting.) |
ReeceGoding (talk | contribs) m (→{{header|R}}: Syntax improvement.) |
||
Line 5,020: | Line 5,020: | ||
=={{header|R}}== |
=={{header|R}}== |
||
The previously solution missed out on a cool R trick for swapping items and had no check for lists of length 1. As R is 1-indexed, we have aimed to be as faithful as we can to the given pseudo-code. |
The previously solution missed out on a cool R trick for swapping items and had no check for lists of length 1. As R is 1-indexed, we have aimed to be as faithful as we can to the given pseudo-code. |
||
<lang rsplus>bubbleSort<-function(items) |
<lang rsplus>bubbleSort <- function(items) |
||
{ |
{ |
||
repeat |
repeat |
||
{ |
{ |
||
if((itemCount<-length(items))<=1) return(items) |
if((itemCount <- length(items)) <= 1) return(items) |
||
hasChanged<-FALSE |
hasChanged <- FALSE |
||
itemCount<-itemCount-1 |
itemCount <- itemCount - 1 |
||
for(i in |
for(i in seq_len(itemCount)) |
||
{ |
{ |
||
if(items[i]>items[i+1]) |
if(items[i] > items[i + 1]) |
||
{ |
{ |
||
items[c(i,i+1)]<-items[c(i+1,i)]#The cool trick mentioned above. |
items[c(i, i + 1)] <- items[c(i + 1, i)]#The cool trick mentioned above. |
||
hasChanged<-TRUE |
hasChanged <- TRUE |
||
} |
} |
||
} |
} |
||
Line 5,040: | Line 5,040: | ||
} |
} |
||
#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}} |