function
partition(list, left, right, pivotIndex)
pivotValue := list[pivotIndex]
swap list[pivotIndex] and list[right] // Move pivot to end
storeIndex := left
for
i from
left to
right
if
list[i] < pivotValue
swap list[storeIndex] and list[i]
increment storeIndex
swap list[right] and list[storeIndex] // Move pivot to its final place
return
storeIndex
function
select(list, left, right, k)
if
left = right // If the list contains only one element
return
list[left] // Return that element
select pivotIndex between left and right
pivotNewIndex := partition(list, left, right, pivotIndex)
pivotDist := pivotNewIndex - left + 1
// The pivot is in its final sorted position,
// so pivotDist reflects its 1-based position if list were sorted
if
pivotDist = k
return
list[pivotNewIndex]
else if
k < pivotDist
return
select(list, left, pivotNewIndex - 1, k)
else
return
select(list, pivotNewIndex + 1, right, k - pivotDist)
function
select(list, left, right, k)
loop
select pivotIndex between left and right
pivotNewIndex := partition(list, left, right, pivotIndex)
pivotDist := pivotNewIndex - left + 1
if
pivotDist = k
return
list[pivotNewIndex]
else if
k < pivotDist
right := pivotNewIndex - 1
else
k := k - pivotDist
left := pivotNewIndex + 1
quickselect
最新推荐文章于 2025-03-15 16:45:34 发布
本文深入解析了快速选择算法的核心逻辑,包括分区函数、选择函数及其优化策略,详细阐述了算法的工作原理、实现细节以及实际应用。
926

被折叠的 条评论
为什么被折叠?



