Skip to content

Instantly share code, notes, and snippets.

@anj1
Last active November 19, 2015 09:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anj1/2fe551053c849f54677e to your computer and use it in GitHub Desktop.
Save anj1/2fe551053c849f54677e to your computer and use it in GitHub Desktop.
# Lazy quicksort.
# Can be used to take only the first k elements of the sorted array,
# And will do this 'efficiently'
lazysort{T}(lst::Vector{T}) =
@task begin
if length(lst) == 0 # is sorting trivial?
elseif length(lst) == 1
produce(lst[1])
else
# take pivot element
pivot = lst[rand(1:length(lst))]
# partition array
lt, gt = T[], T[]
for i in lst
push!(i <= pivot ? lt : gt, i)
end
# sort subdivided
for i in lazysort(lt); produce(i); end
for i in lazysort(gt); produce(i); end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment