Labels

algorithms (22) Design Patterns (20) java (19) linux (14) Snippet (13) service mix (6) soa (4)

Kth Element in a list

int findKthElement(Object[] objects, int kth) {
        System.out.println("findKte");
        int i = rd.nextInt(objects.length);
        ArrayList listOne = new ArrayList<>();
        ArrayList listTwo = new ArrayList<>();
        for (int j = 0; j < objects.length; j++) {
            if ((int) objects[j] < (int) objects[i]) {
                listOne.add(objects[j]);
            } else if ((int) objects[j] > (int) objects[i]) {
                listTwo.add(objects[j]);
            }
        }
 
        if (kth <= listOne.size()) {
            return findKthElement(listOne.toArray(), kth);
        } else if (kth > (objects.length - listTwo.size())) {
            return findKthElement(listTwo.toArray(), kth
                    - (objects.length - listTwo.size()));
        } else {
            return (int) objects[i];
        }
    }

No comments:

Post a Comment

Search 24 Bytes