Skip to content

Instantly share code, notes, and snippets.

@hpoit
Last active March 13, 2018 23:06
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/9c56497581d56ae8547ae5bd1c4c8667 to your computer and use it in GitHub Desktop.
Save hpoit/9c56497581d56ae8547ae5bd1c4c8667 to your computer and use it in GitHub Desktop.
Khan quick sort
# https://rosettacode.org/wiki/Sorting_algorithms/Quicksort#Julia
julia> function quicksort_ex!(A, i=1, j=length(A))
if j > i
pivot = A[rand(i:j)] # random element of A
left, right = i, j
while left <= right
while A[left] < pivot # partition
left += 1
end
while A[right] > pivot # partition
right -= 1
end
if left <= right
A[left], A[right] = A[right], A[left]
left += 1
right -= 1
end
end
quicksort_ex!(A,i,right)
quicksort_ex!(A,left,j)
end
return A
end
quicksort_ex! (generic function with 3 methods)
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 quicksort_ex!(copy(v))
0.022634 seconds (2.62 k allocations: 155.695 KiB)
100-element Array{Int64,1}:
-100
-100
-100
-99
-99
-99
-98
-97
-94
-94
83
83
84
85
89
91
91
93
95
julia>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment