Suzi
Suzi

Reputation: 11

Trying to sort a vector of elements in R

Can someone tell me what I am doing wrong? I was trying to build bubble sort mechanism on a given vector using R, but it throws me an error. v[1] refers to first element of v i.e 6.

v <- c(6,2,5,8)
c <- 1
n <- length(v)
   while(c <- n){
     if(v[c + 1] < v[c]){
      v[c] <- v[c] + v[c+1]
      v[c+1] <- v[c] - v[c+1]
      v[c] <- v[c] - v[c+1]
      c <- c + 1
      }else{
      c <- c + 1
   }
  return(v)
}

Upvotes: 1

Views: 58

Answers (3)

Rui Barradas
Rui Barradas

Reputation: 76673

It's been a [long] while since I've programmed a bubble sort but I can still remember it well. There are several ways to implement it, here's one.

changed <- TRUE
while(changed){
    changed <- FALSE
    for(i in seq_along(v)[-length(v)]){
        if(v[i] > v[i + 1]){
            v[i] <- v[i] + v[i + 1]
            v[i + 1] <- v[i] - v[i + 1]
            v[i] <- v[i] - v[i + 1]
            changed <- TRUE
        }
    }
}

v
[1] 2 5 6 8

As for your routine, apart from what Jordy Brinks said, there's also the fact that your while loop would only do one pass through the vector, giving you a O(n) sort! The algorithm is wrong...
And you shouldn't put c <- c + 1 on both branches of the if/else statement, put it right after it.

Upvotes: 0

sneakyErich
sneakyErich

Reputation: 66

I think you are looking for this:

sort(v)

Cheers

Upvotes: 0

Jordy Brinks
Jordy Brinks

Reputation: 85

A syntax error I found from googling the syntax of R: in your while loop you say (c <- n). This should be (c <= n)

Upvotes: 1

Related Questions