使用R语言进行冒泡排序? [英] Bubble sort using R language?

查看:413
本文介绍了使用R语言进行冒泡排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程方面的新手,我刚刚开始学习R语言。我正在尝试进行冒泡排序,但是显示以下错误消息。谁能帮我解决问题?

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)




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

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


推荐答案

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()函数。

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

这篇关于使用R语言进行冒泡排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆