减治法——搜索第k小元素(Decrease and Conquer by a Factor - Finding the kth smallest element)
问题(Problem)
Find the kth smallest element in an unsorted array.
分割(Partitioning)
Partitioning an array around some pivot element p means reorganising the array so that all elements to the left of p are no greater than p, while those to the right are now smaller.
Lomuto Partitioning
function LomutoPartition(A[lo..hi])
p ⟵ A[lo]
s ⟵ lo
for i ⟵ lo+1 to hi do
if A[i] < p then
s ⟵ s + 1
swap(A[s], A[i])
swap(A[lo], A[s])
return s
算法代码(Algorithm Pseudocode)
function QuickSelect(A[lo, hi], k)
s ⟵ LomutoPartition(A[lo..hi])
if s = lo + k - 1 then
return A[s]
if s < lo + k -1 then
QuickSelect(A[s+1..hi], k-s-1)
else
QuickSelect(A[lo..s-1], k)
Java code
I will update ASAP.
最后再说两句(PS)
Welcome questions always and forever.