Vous êtes sur la page 1sur 1

Estructura de Datos

Sascha Alexander Pedersbeck Franco Pgina 1



Mtodo Bsqueda Binaria en JAVA

public class BusquedaBinaria
{
public static int busquedaBinaria(int[] Arreglo, int elemento)
{
int i = 0, centro = 0, posicion = 0, inferior = 0, superior = Arreglo.length-1;

while(inferior <= superior)
{
centro = (superior + inferior) / 2;

if (Arreglo[centro] == elemento)
return centro;

else
if (Arreglo[centro] > elemento)
superior = centro - 1;
else
inferior = centro + 1;
}

return -1;
}

public static void main (String[] args)
{
java.util.Scanner Leer = new java.util.Scanner(System.in);

System.out.print( " Tamao del array: " );
int tamaoArreglo = Leer.nextInt();

int[] Arreglo = new int[tamaoArreglo];

for(int i=0; i<Arreglo.length; i++)
Arreglo = Leer.nextInt();

System.out.print( " Elemento que se busca: " );
int elemento = Leer.nextInt();

int posicion = busquedaBinaria(Arreglo, elemento);

if(posicion == -1)
System.out.println("El elemento no existe " );
else
System.out.println(" Elemento " + elemento + " encontrado en el lugar " + posicion);
}
}

Vous aimerez peut-être aussi