Binary search, return of all elements of an array that are equal

2

The binary search always returns the first element that is equal to the one we are looking for, but as we could do to return the positions of all the elements that are equal to the one we are looking for, for example, we have a vector of:

H-H-J-O

If I use a binary search, looking for H, will it tell me that the H is in position 0, ignoring the second one in position 1, is there any way to adapt the search to return the position of all the elements? In this case the output would be, the H is in position 0 and in position 1 thanks in advance

    
asked by Rafael Valls 18.11.2017 в 11:56
source

1 answer

0

Simpleemtne what you have to do is that the way to get the positions, instead of returning a single number, you return more than one number.

import java.util.ArrayList;
import java.util.List;

public class Menu {

    public static void main(String[] args) {
        char[] vectorCaracter = new char[4];

        vectorCaracter[0] = 'H';
        vectorCaracter[1] = 'H';
        vectorCaracter[2] = 'J';
        vectorCaracter[3] = 'O';

        char valorBusqueda = 'H';

        List<Integer> listaPosiciones = obtenerPosiciones(vectorCaracter, valorBusqueda);

        for (Integer posicion : listaPosiciones) {
            System.out.println("El caracter "+ valorBusqueda + " se encuentra en la posicion " + posicion);
        }

        System.exit(0);

    }

    private static List<Integer> obtenerPosiciones(char[] vectorCaracter, char valorBusqueda) {
        List<Integer> listaPosiciones = new ArrayList<Integer>();

        for (int i = 0; i < vectorCaracter.length; i++) {
            if (vectorCaracter[i] == valorBusqueda) {
                listaPosiciones.add(i);
            }
        }

        return listaPosiciones;
    }

}
    
answered by 18.11.2017 / 16:43
source