Julia is lightning fast: bubble sort revisited
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.