# [R] Merge sort

Gaston dpv at gmx.ch
Tue Apr 19 21:39:33 CEST 2016

```Hello everyone,

I am learning R since recently, and as a small exercise I wanted to
write a recursive mergesort. I was extremely surprised to discover that
my sorting, although operational, is deeply inefficient in time. Here is
my code :

> merge <- function(x,y){
>   if (is.na(x)) return(y)
>   else if (is.na(y)) return(x)
>   else if (x<y) return(c(x,merge(x[-1],y)))
>   else return(c(y,merge(x,y[-1])))
> }
>
> division <- function(x){
>   if (is.na(x)) return(cbind(x,x))
>   else
> return(cbind(c(x,division(x[-c(1,2)])[,1]),c(x,division(x[-c(1,2)])[,2])))
> }
>
> mergesort <- function(x){
>   if (is.na(x)) return(x)
>   else{
>     print(x)
>     t=division(x)
>     return(merge(mergesort(t[,1]),mergesort(t[,2])))
>   }
> }

I tried my best to write it "the R-way", but apparently I failed. I
suppose some of the functions I used are quite heavy. I would be
grateful if you could give a hint on how to change that!

I hope I made myself clear and wish you a nice day,

Cheers,

Gaston

[[alternative HTML version deleted]]

```