package java_programs;
import java.util.*;

public class KTH {
    public static Integer kth(ArrayList<Integer> arr, int k) {
        if (arr == null || arr.isEmpty()) {
            throw new IllegalArgumentException("Array is empty or null");
        }
        if (k < 0 || k >= arr.size()) {
            throw new IllegalArgumentException("Index k is out of bounds");
        }

        int pivot = arr.get(0);
        ArrayList<Integer> below, equals, above;
        below = new ArrayList<Integer>();
        equals = new ArrayList<Integer>();
        above = new ArrayList<Integer>();
        
        for (Integer x : arr) {
            if (x < pivot) {
                below.add(x);
            } else if (x > pivot) {
                above.add(x);
            } else {
                equals.add(x);
            }
        }
        
        int num_less = below.size();
        int num_lessoreq = num_less + equals.size();
        
        if (k < num_less) {
            return kth(below, k);
        } else if (k >= num_lessoreq) {
            return kth(above, k - num_lessoreq);
        } else {
            return pivot;
        }
    }
}