Skip to content

Instantly share code, notes, and snippets.

@hpoit
Last active March 13, 2018 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hpoit/38f52c826074181d90e3cee560c209a2 to your computer and use it in GitHub Desktop.
Save hpoit/38f52c826074181d90e3cee560c209a2 to your computer and use it in GitHub Desktop.
Cormen_232 - sort and merge
https://rosettacode.org/wiki/Sorting_algorithms/Merge_sort#Julia
julia> function mergesort(arr::Vector)
if length(arr) ≤ 1 return arr end
mid = length(arr) ÷ 2
lpart = mergesort(arr[1:mid])
rpart = mergesort(arr[mid+1:end])
rst = similar(arr)
i = ri = li = 1
@inbounds while li ≤ length(lpart) && ri ≤ length(rpart)
if lpart[li] ≤ rpart[ri]
rst[i] = lpart[li]
li += 1
else
rst[i] = rpart[ri]
ri += 1
end
i += 1
end
if li ≤ length(lpart)
copy!(rst, i, lpart, li)
else
copy!(rst, i, rpart, ri)
end
return rst
end
mergesort (generic function with 1 method)
julia> v = rand(-100:100, 100)
100-element Array{Int64,1}:
-69
23
-23
66
25
-58
-63
-83
-58
63
-25
-61
-51
-70
-72
73
-92
43
24
julia> @time println("# unordered: $v\n -> ordered: ", mergesort(v))
# unordered: [-69, 23, -23, 66, 25, -58, -63, -83, -58, 63, -47, 72, 95, -39, -90, -73, -52, -10, -17, 46, -99, -28, 55, 20, 58, 5, -99, -92, 83, 19, -94, -45, 66, -100, -58, 83, 32, -9, -62, -3, 60, -100, -30, -98, -35, -64, -2, -67, -94, -93, -62, 45, 91, -22, -85, 70, -97, 29, 15, -99, -36, -23, 91, -29, 64, -69, -100, -7, 43, -38, -29, 93, -29, 89, 30, 79, -51, 4, -31, 23, -72, 14, 41, 79, 24, 85, -64, -41, 84, 83, 17, -25, -61, -51, -70, -72, 73, -92, 43, 24]
-> ordered: [-100, -100, -100, -99, -99, -99, -98, -97, -94, -94, -93, -92, -92, -90, -85, -83, -73, -72, -72, -70, -69, -69, -67, -64, -64, -63, -62, -62, -61, -58, -58, -58, -52, -51, -51, -47, -45, -41, -39, -38, -36, -35, -31, -30, -29, -29, -29, -28, -25, -23, -23, -22, -17, -10, -9, -7, -3, -2, 4, 5, 14, 15, 17, 19, 20, 23, 23, 24, 24, 25, 29, 30, 32, 41, 43, 43, 45, 46, 55, 58, 60, 63, 64, 66, 66, 70, 72, 73, 79, 79, 83, 83, 83, 84, 85, 89, 91, 91, 93, 95]
0.562905 seconds (239.82 k allocations: 11.999 MiB)
julia>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment