您的位置:首页 > 产品设计 > UI/UE

减治法——搜索第k小元素(Decrease and Conquer by a Factor - Finding the kth smallest element)

2017-06-11 16:32 357 查看

减治法——搜索第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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐