Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bubble sort using R language?

Tags:

r

bubble-sort

I am new in programming, and I just start learning R language. I am trying to do a bubble sort, but it shows the following error message. Can anyone help me solve the problem?

x <-sample(1:100,10)
n <- length(x)
example <- function(x)
{
  for (i in 1:n-1)
  {
   while (x[i] > x[i+1])
      {
      temp <- x[i+1]
      x[i+1] <- x[i]
      x[i] <- temp
      }
  i <- i+1
  }
}

example(x)

Error in while (x[i] > x[i + 1]) { : argument is of length zero

like image 505
Andy Avatar asked Mar 17 '16 03:03

Andy


People also ask

What are 3 sorting algorithms available in R?

The sorting algorithms present in R are as follows: Bucket Sort. Selection Sort. Quick Sort.

How do I sort in R?

To sort a data frame in R, use the order( ) function. By default, sorting is ASCENDING. Prepend the sorting variable by a minus sign to indicate DESCENDING order.

What is bubble sort with example?

Bubble sort starts with very first two elements, comparing them to check which one is greater. ( 5 1 4 2 8 ) –> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. ( 1 5 4 2 8 ) –> ( 1 4 5 2 8 ), Swap since 5 > 4.


1 Answers

x<-sample(1:100,10)
example <- function(x){
  n<-length(x)
  for(j in 1:(n-1)){
    for(i in 1:(n-j)){
      if(x[i]>x[i+1]){
        temp<-x[i]
        x[i]<-x[i+1]
        x[i+1]<-temp
      }
    }
  }
  return(x)
}
res<-example(x)
#input
x
#output
res

It is working fine with little modification of your code. In 'R' it is better to use sort() function.

x <-sample(1:100,10)
x
res<-sort(x)
res
like image 153
venkatachalam.j Avatar answered Sep 30 '22 00:09

venkatachalam.j