在不使用排序函数的情况下对 R 中的向量进行排序

Kar*_*k S 1 for-loop if-statement r

我正在尝试编写一个函数来对向量进行排序,但没有使用 R 的内置“排序”函数。我的代码:

sorting <- function(x){
  for(i in 1:length(x)){
    for(j in (i+1):length(x)){
      if(x[i] > x[j]){
        x[c(i,j)] = x[c(j,i)]
      }
    }
  }
  x
}
Run Code Online (Sandbox Code Playgroud)

我得到以下输出:

> x <- c(3,1,4,7,2,9)
> sorting(x)
Error in if (x[i] > x[j]) { : missing value where TRUE/FALSE needed
> 
Run Code Online (Sandbox Code Playgroud)

我知道当 'IF' 条件返回 'NA' 而不是 TRUE/FALSE 时,我们会得到上述错误。

声明是否有问题:

for(j in (i+1):length(x)){
Run Code Online (Sandbox Code Playgroud)

相同的 Python 代码:

def sorting(a):
    for i in range(len(a)):    
        for j in range(i+1,len(a)):
            if a[i] > a[j]:
                a[i],a[j] = a[j],a[i]

    return a
Run Code Online (Sandbox Code Playgroud)

输出:

sorting([3,1,4,7,2,9])
Out[380]: [1, 2, 3, 4, 7, 9]
Run Code Online (Sandbox Code Playgroud)

在 Python 中,代码运行良好。

有人可以让我知道我的 R 代码的问题。

RLa*_*ave 5

问题就在于此(i+1)。当length(x)达到最大值时,j超出范围。我补充说:(length(x)-1)

sorting <- function(x){
  for(i in 1:(length(x)-1)){
    for(j in (i+1):length(x)){
      if(x[i] > x[j]){
        x[c(i,j)] = x[c(j,i)] # +1 for this
      }
    }
  }
  x
}

sorting(c(3,1,4,7,2,9))
[1] 1 2 3 4 7 9
Run Code Online (Sandbox Code Playgroud)