Julia is lightning fast: bubble sort revisited

December 26, 2013
By

(This article was first published on NumberTheory » R stuff, and kindly contributed to R-bloggers)

I had heard the name of the new technical computing language Julia buzzing around for some time already. Now during Christmas I had some time on my hands, and implemented the bubble sort algorithm that I have already posted about several times (R, C++). The main argument for Julia is it’s speed. It claims speeds comparable to that of a compiled language such as C++, but in the form of a high-level programming language such as R or Matlab.

The following Julia code implements the bubble sort algorithm, in the same style as the C++ algorithm I implemented using Rcpp.

function swap_vector(vec_in, passes)
    no_swaps = 0 
    for vec_index in [1:(length(vec_in) - 1 - passes)]
        if vec_in[vec_index] > vec_in[vec_index + 1]
            no_swaps += 1
            tmp = vec_in[vec_index]
            vec_in[vec_index] = vec_in[vec_index + 1]
            vec_in[vec_index + 1] = tmp 
        end 
    end 
    return no_swaps
end

function sort_julia(vec_in)
    passes = 0 
    while(true)
        no_swaps = swap_vector(vec_in, passes)
        if no_swaps == 0 
            break
        end 
        passes += 1
    end 
    return vec_in
end

n = 10000
repeat = 10

for index in [1:repeat]
    unsorted_vec = rand(Int32, n)
    println(@elapsed bla = sort_julia(unsorted_vec))
end

Running this from the command line leads to the following timings in seconds:

$ julia sort_julia.jl 
0.4039602
0.37794618
0.382728631
0.376510427
0.376038704
0.382480906
0.376912447
0.370066738
0.387273682
0.376426721

This is in the same order of magnitude as the C++ implementation, which leads to timings of around 0.31 secs. So, this first examples shows that Julia is comparable in speed to C++ for this example, which is much much faster than the same implementation would be in R.

Julia certainly lacks the maturity of a tool such as R or Python, but the speed is impressive and I like the clean looking syntax. I’m curious to see where Julia will go from here, but I’ll certainly try and find an excuse to try Julia out for a real project.

To leave a comment for the author, please follow the link and comment on his blog: NumberTheory » R stuff.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.