A collection of humorous and impractical sorting algorithms in Julia.
Published
June 7, 2025
Stalins Sort
Tired of inefficiency inside your sorting allgorithms. I present Stalins sort. With an asymtotic complexety of only \(\mathcal{O}(n)\). The only downside is that some values might end up inside the gulag
functionstalins_sort(A::Vector{T})::Vector{T} where T <: Any last::T = A[1] B =Vector{T}([last])for i in2:length(A)if last < A[i]push!(B, A[i]) last = A[i]endendreturn Bendprintln("perfectly sorted array:")@showstalins_sort([4, 3, 5, 9, 2, 1, 6, 8, 7])nothing# display nothing
Why limit oneself to deterministic algorithms? Random sort is a sorting algorithm that randomly shuffles the input until it is sorted. It has an expected time complexity of \(\mathcal{O}(n!)\) but a space complexity of just \(\mathcal{O}(n)\) in nondeterministic machienes.
functionrandom_sort(A::Vector{T})::Vector{T} where T <: Any B =copy(A)while !issorted(B)# shuffle the arrayfor i in1:length(B) j =rand(1:length(B)) B[i], B[j] = B[j], B[i]endendreturn Bendprintln("randomly sorted array:")@showrandom_sort([4, 3, 5, 9, 2, 1, 6, 8, 7])nothing# display nothing
Haters would say that this algorithm never terminates, but experts know that there is a real chance of cosmic rays hitting the computer and flipping enoth bits to make the while condition true and thereby effectivly sorting the array.
functionmiracle_sort!(A::Vector{T})::Vector{T} where T <: Anywhile !issorted(A)# sleep for 1 secsleep(1)endreturn Aendprintln("sorted array:")@showmiracle_sort!([4, 3, 5, 9, 2, 1, 6, 8, 7])nothing# display nothing