recur by using the pivot in Select algorithm

二次信任 提交于 2019-12-31 02:45:13

问题


I have a problem and I can not get the purpose of lines (14,15,16,17) of this site for Select algorithm.

The site which had this question was located here.

EDITED: Also, is this correct to write these lines for the part "partition and recur by using the pivot"? ("m" is my pivot and "i" is the input of this algorithm)

         arrOne<--{a of arr : a<m}
         arrTwo<--{a of arr : a>m}
         if    (i < m ) then
               return Select(arrOne,i)
         else if (i > m)  then
                return Select(arrTwo,i-m)
         else 
                return m

回答1:


This is where it selects the partition in which to recurse.

For the sake of illustration, let's assume you're looking for the median of an array with 100 elements. The first time you partition, you get partitions of, say, 60 and 40 items. Since you're looking for the 50th item, you know it must be in the left partition (which has 60 items).

You then partition that, and get, we'll say, left and right partitions of 25 and 35 items respectively. This time we can see that the 50th item must be in the right partition, so we recurse into that one.

We continue this until we reach a partition that contains only one item -- the one we're looking for.



来源:https://stackoverflow.com/questions/3074372/recur-by-using-the-pivot-in-select-algorithm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!