QuickSelect Algorithm Understanding
Partition is pretty simple: it rearranges the elements so those less than a selected pivot are at lower indices in the array than the pivot and those larger than the pivot are at higher indices in the array.
I talked about the rest it in a previous answer.
int quickSelect(int A[], int l, int h,int k)
{
int p = partition(A, l, h);
if(p==(k-1)) return A[p];
else if(p>(k-1)) return quickSelect(A, l, p - 1,k);
else return quickSelect(A, p + 1, h,k);
}
// partition function same as QuickSort
btw, your code has a few bugs..
int quickSelect(int items[], int first, int last, int k) {
int pivot = partition(items, first, last);
if (k < pivot-first+1) { //boundary was wrong
return quickSelect(items, first, pivot, k);
} else if (k > pivot-first+1) {//boundary was wrong
return quickSelect(items, pivot+1, last, k-pivot);
} else {
return items[pivot];//index was wrong
}
}
The important part in quick select is partition. So let me explain that first.
Partition in quick select picks a pivot
(either randomly or first/last element). Then it rearranges the list in a way that all elements less than pivot
are on left side of pivot and others on right. It then returns index of the pivot
element.
Now here we are finding kth smallest element. After partition cases are:
k == pivot
. Then you have already found kth smallest. This is because the way partition is working. There are exactlyk - 1
elements that are smaller than thekth
element.k < pivot
. Then kth smallest is on the left side ofpivot
.k > pivot
. Then kth smallest is on the right side of pivot. And to find it you actually have to findk-pivot
smallest number on right.