I'm trying to implement quickselect by partitioning the array, but it constantly produces wrong answers. Where am I committing a mistake?

Viewed 2

Here's the java code

The select function returns the kth smallest element present in the array. Even though the code seems alright to me, it does not produce the correct results.

public static Comparable select(Comparable[] a, int k, int lo, int hi) {
        if(hi <= lo) return a[--k];

        int j = partition(a, lo, hi);
        if(j == k-1) return a[j];
        else if(j > k-1) return select(a, k, lo, j-1);
        else if(j < k-1) return select(a, k, j+1, hi);

        return a[--k];
    }

    private static int partition(Comparable[] a, int lo, int hi) {
        int i = lo, j = hi;
        Comparable pivot = a[lo + (hi - lo)/2]; // the pivot element;

        while(i < j) {
            while(less(a[++i], pivot)) if(i == hi) break;
            while(less(pivot, a[--j])) if(j == lo) break;

            exchange(a, i, j); // exchanges elements at indices i and j
        }
        exchange(a, lo, j); // exchanges elements at indices lo and j

        return j; 
    }
0 Answers
Related