使用R语言进行冒泡排序?

5

我是个编程新手,刚开始学习 R 语言。我想尝试做一个冒泡排序,但是出现了以下错误信息。有谁能帮我解决这个问题吗?

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)

在 while (x[i] > x[i + 1]) { 中出现错误:参数长度为零


4
附注:1:n-1 可能应该改为 1:(n-1) - Rich Scriven
1
另外,该函数没有返回任何内容。也许还有其他问题? - G. Grothendieck
除了Richard所说的,尝试使用1:10-11:(10-1)来查看为什么会出现错误。 - JeremyS
我现在没有看到任何错误信息。但是似乎“While”和“for”循环根本不起作用。结果显示原始X,而不是排序后的X。有什么评论吗? - Andy
@Andy,你指定了返回值吗? - ytk
我想返回排序后的X,但不确定在哪里添加它。 - Andy
3个回答

4
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

稍微修改一下您的代码就可以正常工作。在'R'中最好使用sort()函数。

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

1
你的排序算法存在一些不准确之处。我已经进行了修改以使其正常运行。
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

顺便提一下,R语言有很多用于处理事情的函数和方法。这个example函数可以作为一个学习例子,但我建议在解决实际问题时使用现有的sort函数。

在R语言中,应该尽量避免使用循环,并利用向量化函数来加快代码速度。


1
我知道使用“temp”变量是交换两个变量的经典方法,但在R中,您可以使用“x[c(i,i+1)] = x[c(i+1,i)]”来实现。 - Spacedman

0

它会给你这个错误信息,因为它无法比较一个超出其范围的值,而在你的情况下是 (x[i] > x[i + 1])。如果你想按降序对数组进行排序,请尝试以下方法:

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
  }

}

对于递增顺序,你只需要在while循环中切换>符号即可。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接