vendredi 8 février 2019

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.

Aucun commentaire:

Enregistrer un commentaire