0

So I am going through the Quick select algorithm from the CLRS book and I understand the whole concept of the algorithm. But one thing that I am not able to grasp is the initial condition they have at the top. Following is my implementation of the algorithm from the book:

private int quickSelect(int[] arr, int p, int r, int i){
    
    if(r==p){
        return arr[p];
    }

    int q=partition(arr,p,r);

    if(i-1==q){
        return arr[q];
    }
    else if(i-1<q){
        return quickSelect(arr,p,q-1,i);
    }
    else{
        return quickSelect(arr,q+1,r,i);
    }

}

Here, why do we check if p==r and return arr[p]? The value of position i passed might not be the same as p/r. If they give a value higher than the array length, then this would not make sense. Instead of that, it would be better to throw an exception after checking it. I went through a lot of resources on the internet and some of them also use the same condition at the start. QuickSelect Algorithm In this post, it is given that the condition is to check if there is only one element is present but I am not sure how that works.

  • 1
    The condition isn't there to catch bad input passed in from outside; it is there to catch the base case: When there is only one element in the array, it must be the pivot. If p ≤ i − 1 ≤ r on the first call (from oustide), the conditions for recursing guarantee that condition throughout. – M Oehm May 10 '22 at 14:18
  • @MOehm, So you mean when we call the select algorithm with just one element, that condition is used. But even without that, we can still use the partition method on just one element array and it'll return the result. And since we are going to get a value for sure since we are just choosing a value at a specific position, do we need a base case like that? isn't the position found condition the base case for this recursive func? – Gopalakrishnan Ganesan May 10 '22 at 16:24
  • Yes, you can get at the same result with partitioning, but it saves you some work. But a null partitioning is fast anyway, so perhaps not much. And you are also correct that the actual base case is when the pivot is at the requested position; you can't remove that condition, of course. – M Oehm May 10 '22 at 17:48

0 Answers0