I am having a problem understanding the Quick select algorithm. I know it is based on the Quick sort algorithm (which I am familiar with) and that it gives you the required result perhaps leaving a portion of the array unsorted.Now here is where I am having difficulty. The question is find the 2nd smallest element from the array which is:
int a[4] = {1,3,5,2} ;
Now suppose we are selecting pivot randomly then according to this post we have the following conditions:
k == pivot
. Then you have already found kth smallest. This is because the way partition is working. There are exactly k - 1 elements that are smaller than the kth element.k < pivot
. Then kth smallest is on the left side of pivot.k > pivot
. Then kth smallest is on the right side of pivot. And to find it you actually have to find k-pivot smallest number on right.
I would appreciate it if someone could explain how k==pivot
means that we have found the kth (in my case the 2nd smallest element). Also if its k < pivot
do we repeat the process for the left side of the pivot ?