Skip to content

Commit

Permalink
Almost working quickselect that will pave the way for median and
Browse files Browse the repository at this point in the history
order statistics.
  • Loading branch information
ViralBShah committed Dec 24, 2011
1 parent dd501da commit 51d055d
Showing 1 changed file with 33 additions and 0 deletions.
33 changes: 33 additions & 0 deletions examples/select.j
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# http://en.wikipedia.org/wiki/Selection_algorithm#Partition-based_general_selection_algorithm

function _jl_quickselect(a::AbstractVector, k::Integer, lo::Integer, hi::Integer)
while true
#partition(a, lo, hi, m)
i, j = lo, hi
pivot = a[div(lo+hi, 2)]
while i <= j
while a[i] < pivot; i += 1; end
while pivot < a[j]; j -= 1; end
if i <= j
a[i], a[j] = a[j], a[i]
i += 1
j -= 1
end
end

pivot_new = j + 1
pivot_dist = pivot_new - lo + 1
if pivot_dist == k
return a[pivot_new]
elseif k < pivot_dist
hi = pivot_new - 1
else
k = k - pivot_dist
lo = pivot_new + 1
end

end
end

select(a::AbstractVector, k::Integer) = _jl_quickselect(copy(a), k, 1, length(a))
select!(a::AbstractVector, k::Integer) = _jl_quickselect(a, k, 1, length(a))

0 comments on commit 51d055d

Please sign in to comment.