Average Runtime of Quickselect

后端 未结 3 708
渐次进展
渐次进展 2020-12-05 00:14

Wikipedia states that the average runtime of quickselect algorithm (Link) is O(n). However, I could not clearly understand how this is so. Could anyone explain to me (via r

3条回答
  •  臣服心动
    2020-12-05 01:02

    In quickselect, as specified, we apply recursion on only one half of the partition.

    Average Case Analysis:

    First Step: T(n) = cn + T(n/2)

    where, cn = time to perform partition, where c is any constant(doesn't matter).
    T(n/2) = applying recursion on one half of the partition.
    Since it's an average case we assume that the partition was the median.

    As we keep on doing recursion, we get the following set of equation:

    T(n/2) = cn/2 + T(n/4)
    T(n/4) = cn/2 + T(n/8)
    .
    .
    .
    T(2) = c.2 + T(1)
    T(1) = c.1 + ...

    Summing the equations and cross-cancelling like values produces a linear result.

    c(n + n/2 + n/4 + ... + 2 + 1) = c(2n) //sum of a GP

    Hence, it's O(n)

提交回复
热议问题