Finding the kth smallest item in an array using quicksort => expected running time?

青春壹個敷衍的年華 提交于 2020-01-04 06:35:26

问题


If I am using a modified version of quicksort to find the kth smallest item in an array, why is the expected running time O(n) (as stated by Programming Pearls book)?

The algorithm I'm using does the following:

1) Runs quick sort on the array
2) If k is > the correct location of pivot, then run quicksort on the 2nd half.
Otherwise run it on the first half.

I was under the impression this would take O(n * logn) work.


回答1:


This link, may help to understand the proof for randomized quick select, http://pine.cs.yale.edu/pinewiki/QuickSelect,

Idea behind getting Kth order statistic is, select a pivot, and partition the data as suggested by quick sort and find out which partition the element being searched for lies in. Partitioning has the complexity of O(n). After partitioning, you need to pick, just one of resulting partition for further processing unlike quick sort, where you have to process both.

In the below description, I am not trying to prove, but wanted to give intuitive thoughts to understand the expected complexity,

For simplicity, let us assume, on every iteration, pivot splits the array in equal halves, then the complexity is clearly O(n), as

   n + (n/2) + (n/4) ... <= c.n, O(n)

For intuitive understanding, getting a worst case partitioning, where you would have to process (n-1) elements in every iteration happens with the probability of just (1/n). So, the worst case complexity is anyway, O(n^2).

Anyways, if you want a rigorous proof for expected complexity, you can go through the link, provided.




回答2:


That won't be the algorithm that's described in the book. More likely it does one partition at (1), (2), etc.



来源:https://stackoverflow.com/questions/17914808/finding-the-kth-smallest-item-in-an-array-using-quicksort-expected-running-ti

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