Julia is lightning fast: bubble sort revisited

December 26, 2013

(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 
    return no_swaps

function sort_julia(vec_in)
    passes = 0 
        no_swaps = swap_vector(vec_in, passes)
        if no_swaps == 0 
        passes += 1
    return vec_in

n = 10000
repeat = 10

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

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

$ julia sort_julia.jl 

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 their blog: NumberTheory » R stuff.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, 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.

Search R-bloggers


Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)