阳光VIP

少壮不努力,老大徒伤悲。平日弗用功,自到临期悔。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

quickselect

Posted on 2012-02-09 22:08  阳光VIP  阅读(178)  评论(0编辑  收藏  举报

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