-1

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; 
    }

1 Answers1

0

The code is using Hoare partition scheme, which means the pivot and elements equal to the pivot can end up anywhere. This means the kth smallest element won't be known until a base case is reached, and this line should be deleted:

        if(j == k-1) return a[j];
rcgldr
  • 27,407
  • 3
  • 36
  • 61