I'm learning basic algorithms in R. I want to create bubble sort algorithm using for loop.
x <- c(20,31,8,46,19)
for (i in 1:length(x)){
if (x[i] > x[i+1]){
temp <- x[i]
x[i] <- x[i+1]
x[i+1] <- temp
cat(x[i],"")
}
else cat (x[i],"")
}
I think in this particular vector, sorting should take place in three "turns.
1st should give a result: 20 8 31 19 46
2nd: 8 20 19 31 46
3rd: 8 19 20 31 46 (correct one)
This loop works out the 1st turn, except printing the last element.
I also don't know how to work out those other "turns". I predict it's something about the other for loop, but I don't know how to implement it.
You're iterating until the last element in x
, but use x[i] > x[i+1]
. So, in the last iteration x[x+1]
is out of bounds. Look into this code which just deals with length(x)-1
iterations plus adds an outside loop which runs from the back to the front of the vector.
bubblesort <- function(x) {
for (j in (length(x)-1):1) {
for (i in j:(length(x)-1)) {
if (x[i] > x[i+1]) {
temp <- x[i]
x[i] <- x[i+1]
x[i+1] <- temp
}
}
}
return(x)
}
x <- c(20,31,8,46,19)
print(x)
print(bubblesort(x))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.