There are functions like factorial
where Julia uses a factorial_lookup
function to directly return results from a table when the value is lower or equal to 20.
Playing around with sorting algorithms I built a simple one that takes into account the size of the vector to sort just like factorial
takes into a account the value passed to calculate its factorial.
As it turns out the algorithm taking into account size is consistently faster than the default for Julia up to a size of five elements, hence my question, why does not Julia uses the same strategy for sort!
as for factorial
considering how critical sorting algorithms are in computing?
Below follows the code and some benchmarks:
function sort2!(x)
swap(i,j) = x[j], x[i] = x[i], x[j]
x[1]>x[2] && swap(1,2)
end
function sort3!(x)
swap(i,j) = x[j], x[i] = x[i], x[j]
if x[1]>x[2] sort2!(x) end
if x[2]>x[3] swap(2,3); sort2!(x) end
end
function sort4!(x)
swap(i,j) = x[j], x[i] = x[i], x[j]
if x[1]>x[2] sort2!(x) end
if x[2]>x[3] swap(2,3); sort2!(x) end
if x[3]>x[4] swap(3,4); sort3!(x) end
end
function sort5!(x)
swap(i,j) = x[j], x[i] = x[i], x[j]
if x[1]>x[2] sort2!(x) end
if x[2]>x[3] swap(2,3); sort2!(x) end
if x[3]>x[4] swap(3,4); sort3!(x) end
if x[4]>x[5] swap(4,5); sort4!(x) end
end
I am just using this algorithm to test the “factorial” idea, I haven’t done any theoretical work on it to guarantee it is sound, to make sure it works I compared its results multiple times with Base.sort!
Comparing benchmarks for vector of length 3 we have:
sort!: 117.439 ns ± 42.243 ns
sort3!: 103.014 ns ± 76.325 ns
Comparing benchmarks for vector of length 5 we have:
sort!: 135.428 ns ± 43.606 ns
sort5!: 128.527 ns ± 60.103 ns
Comparing benchmarks for vector of length 6 we have:
sort!: 148.199 ns ± 45.349 ns
sort6!: 151.984 ns ± 59.283 ns