What is QuickSelect Algorithm?
Suppose I give you an array of numbers and ask you to give me the smallest number. How will you come out with solution?
One simple solution is to sort the array and return the element at index, or ARR[K-1].
C++ code
int kthSmallest(int *arr,int n,int k)
{
sort(arr,arr+n);
return arr[k-1];
}
The time complexity of this approach will be depending upon the sorting algorithm we use. Let us suppose we use the very popular comparison based sorting algorithm known as quicksort.
Since time complexity of quicksort is . Therefore our naive solution will also have the same complexity of .
Is it a good approach?
Surely no because by sorting the whole array, we will be in the position to answer each element from k=1 to k=N ( N is the length of the array). What I want to say is we are doing extra efforts, which we can skip.
Before heading towards our goal, first let us know about the partitioning algorithm.
Partitioning Algorithm
Partitioning algorithm is a subroutine of quicksort algorithm which creates a pivot in the array and returns its index. Elements in the left hand side of the array are less than the pivot and that of right side are greater than the pivot.
for example, if the array is 3,2,1,5,6,4. Then after partitioning it will look like 1,2,3,5,6,4.
It takes the first element and places it at some index such that all elements before it are lesser than it and all element to its right are greater than it.
Here 3 is selected as pivot and placed at index 2.
C++ code
int partition(int *arr,int lb,int ub)
{
int start=lb,end=ub;
int pivot=arr[start];
while(start<end )
{
while(arr[start]<=pivot)
++start;
while(arr[end]>pivot)
--end;
if(start<end)
swap(arr[start],arr[end]);
}
swap(arr[lb],arr[end]);
return end;
}
Time complexity of this partitioning algorithm is .
QuickSelect Algorithm:
Similar to quicksort algorithm, quickselect calls partition function as it subroutine. The partition function partitions the array into two parts and returns the index of the pivot element.
Now, if the index of the pivot element is equal to k, then the quickselect functions returns the pivot, else if k is greater than the pivot index, then the quickselect is called for the right side of the array or if k is less than the pivot index, then the quickseleck is called for the left side of the array.
Look at the code for better understanding.
int quickSelect(int *arr,int start,int end,int k)
{
if(start>end)
return 0;
int pInd=partition(arr,start,end);
if(pInd==k)
return arr[pInd];
if(k>pInd)
{
quickSelect(arr,pInd+1,end,k);
}
else
{
quickSelect(arr,start,pInd-1,k);
}
}
Now let's do the analysis of QuickSelect algorithm:
No comments:
Post a Comment