Bubble sort using R language?

Viewed 9443

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

3 Answers

It gives you that error message because he cannot compare a value that is out of his bounds which is the case for you at (x[i] > x[i + 1]). Try this if you want to sort your array in a decreasing order:

for (i in 1:n){

  j = i

  while((j>1)){
    if ((X[j]> X[j-1])){
    temp = X[j]
    X[j] = X[j-1]
    X[j-1] = temp
    }
    j = j-1
  }

}

For an increasing order you just have to switch around the > sign in the while loop.

Related