Search code examples
javalistgeneric-listdivide-and-conquergeneric-type-argument

How can I get all elements in range from a generic List recursively?


Given a Generic type List (List),and two generic type objects: a,b:

-Design an algorithm that returns a List that contains every element from the original list that belongs to the range [a,b).

-The algorithm must include comparator E.

-The solution must be a "Divide and Conquer" algorithm.

This is what i came up with:

private static <E extends Comparable<E>> List <E> Dominio(List<E> lista, E a, E b){

    return DominioAux(lista,a,b,0,lista.size()-1);
}

private static <E extends Comparable<E>> List <E> DominioAux(List<E> lista, E a, E b,Integer i, Integer j){

    List<E> res = new ArrayList<>();
    Integer m = (j-i)/2;
    E pm = lista.get(m);

    if (pm == a) {
        DominioAux(lista,a,b,m,j);
    } else if(pm==b) {
        DominioAux(lista,a,b,i,m-1);
    }

    if (pm.compareTo(a)<0) {
        res = DominioAux(lista,a,b,m,j);
    }   

    if (pm.compareTo(a)>0) {
        res = DominioAux(lista,a,b,i,m);
    }

    res = lista.subList(i, j);
    return res;     
}

The problem is I either get an "Index out of bounds exception" or an "Stack overflow error" when one of the ifs are executed.


Solution

  • One possible solution using Divide and Conquer paradigm

    private static <E extends Comparable<E>> List <E> DominioAux(List<E> lista, E a, E b,Integer i, Integer j){
        List<E> res = new ArrayList<>();
    
        if(i >= j) { //Check if the value of list[i] is in the range [a,b)
            if (lista.get(i).compareTo(a) >= 0 && lista.get(i).compareTo(b) < 0) {
                res.add(lista.get(i));
            }
    
            return res;
        }
    
        Integer m = (i + j) / 2;
        List<E> list1 = DominioAux(lista, a, b, i, m);
        List<E> list2 = DominioAux(lista, a, b, m + 1, j);
    
        res.addAll(list1);
        res.addAll(list2);
    
        return res;
    }
    

    One mistake in your approach is when calculating the m, m is supposed to be the middle if i and j then to calculate it you must add i and j not subtract i from j