Bubble sort using R language?

我与影子孤独终老i 提交于 2019-12-22 07:47:11

问题


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


回答1:


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



回答2:


You have some inaccuracies in your algorithm of sorting. I've made changes to make it work.

set.seed(1)
x <-sample(1:100,10)
x
# [1] 27 37 57 89 20 86 97 62 58  6
example <- function(x)
{
  n <- length(x) # better insert this line inside the sorting function
  for (k in n:2) # every iteration of the outer loop bubbles the maximum element 
                 # of the array to the end
  {
    i <- 1       
    while (i < k)        # i is the index for nested loop, no need to do i < n
                         # because passing j iterations of the for loop already 
                         # places j maximum elements to the last j positions
    {
      if (x[i] > x[i+1]) # if the element is greater than the next one we change them
      {
        temp <- x[i+1]
        x[i+1] <- x[i]
        x[i] <- temp
      }
      i <- i+1           # moving to the next element
    }
  }
  x              # returning sorted x (the last evaluated value inside the body 
                 # of the function is returned), we can also write return(x)
}

example(x)
# [1]  6 20 27 37 57 58 62 86 89 97

BTW, R language has a lot of functions and methods for doing things. This example function can be a learning example, but I advice to use existing function sort for solving real problems.

In R language you should try to avoid loops and make usage of vectorized functions to make the code faster.




回答3:


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.



来源:https://stackoverflow.com/questions/36051165/bubble-sort-using-r-language

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!