简体   繁体   中英

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.

The problem is with that (i+1) . When length(x) reaches it's 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
Sorting <- function(x){
    xs <- rep(0, length(x))
    for(i in 1:length(x)){
          xs[i] = min(x)
          x <- x[x != min(x)]
          }
    xs
}

Sorting(c(3,1,4,7,2,9))
[1] 1 2 3 4 7 9

Sorting is a function with a numeric vector argument x . Initially xs , the sorted vector of the same length as x , is filled with zeroes. The for loop aims at assigning the minimum value of vector x to each component of xs (for(i in 1:length(x)){ xs[i] = min(x) ) . We then remove such minimum value from x by x <- x[x != min(x)] } to find the next minimum value. Finally, xs shows the sorted vector of x .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM