Mergesort (R)

Page 1 of 1

0 Replies - 1234 Views - Last Post: 10 September 2010 - 07:00 AM

#1 captainhampton

• Jawsome++;

Reputation: 14
• Posts: 548
• Joined: 17-October 07

Mergesort (R)

Posted 10 September 2010 - 07:00 AM

Description: Call the algorithm with a list of integers to perform the sorting algorithm.Performs the mergesort algorithm in R.
```#Uses mergesort to sort a vector
mergesort <- function(x) {
len <- length(x)

#If vector does not require sorting
if (len < 2) result <- x

else{
#Split x in half
y <- x[1:(len/2)]
z <- x[(len/2+1):len]

#Sort y and z
y <- mergesort(y)
z <- mergesort(z)

#Merge y and z to vector
result <- c()

#while some are left in both piles
while(min(length(y),length(z))>0) {

#Put smallest first element on end, remove it from y or z
if (y[1] < z[1]) {
result <- c(result, y[1])
y <- y[-1]
} else{
result <- c(result, z[1])
z <- z[-1]
}
}
#Put what remains on the end result
if (length(y) > 0)
result <- c(result, y)
if (length(z) > 0)
result <- c(result, z)
}
print (result)
return (result)
}

mergesort(c(1,4,8,2,9))
```

Is This A Good Question/Topic? 0

Page 1 of 1