Bubble sort using R language?

Andy picture Andy · Mar 17, 2016 · Viewed 7.4k times · Source

I am new in programming, and I just start learning R language. I am trying to do a bubble sort, but it shows the following error message. Can anyone help me solve the problem?

x <-sample(1:100,10)
n <- length(x)
example <- function(x)
{
  for (i in 1:n-1)
  {
   while (x[i] > x[i+1])
      {
      temp <- x[i+1]
      x[i+1] <- x[i]
      x[i] <- temp
      }
  i <- i+1
  }
}

example(x)

Error in while (x[i] > x[i + 1]) { : argument is of length zero

Answer

venkatachalam.j picture venkatachalam.j · Mar 17, 2016
x<-sample(1:100,10)
example <- function(x){
  n<-length(x)
  for(j in 1:(n-1)){
    for(i in 1:(n-j)){
      if(x[i]>x[i+1]){
        temp<-x[i]
        x[i]<-x[i+1]
        x[i+1]<-temp
      }
    }
  }
  return(x)
}
res<-example(x)
#input
x
#output
res

It is working fine with little modification of your code. In 'R' it is better to use sort() function.

x <-sample(1:100,10)
x
res<-sort(x)
res