首页 > 解决方案 > Sorting a vector in R without using sort function

问题描述

I am trying to write a function to sort a vector, but without using R's inbuilt 'Sort' function. My Code:

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
}

I get below output:

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

I understand that we'll get above error when the 'IF' condition returns 'NA' instead of TRUE/FALSE.

Is there an issue with the statement:

for(j in (i+1):length(x)){

Python code for same:

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

Output:

sorting([3,1,4,7,2,9])
Out[380]: [1, 2, 3, 4, 7, 9]

In Python, the code works fine.

Could someone let me know the issue with my R code.

标签: rfor-loopif-statement

解决方案


The problem is with that (i+1). When length(x) reaches its max value, j goes out of range. I added this: (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

推荐阅读