martes, 26 de noviembre de 2013

Metodo de Busqueda Binaria en Java

El programa tiene un metodo de ordenamiento.


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("Tamanio del arreglo:"); 
int tamanioArreglo = Leer.nextInt(); int[] Arreglo = new int[tamanioArreglo]; 
for(int i=0; i<Arreglo.length; i++){ 
System.out.println("Introduce elemento:"); 
Arreglo[i] = Leer.nextInt();
}
int A;
for(int i=0;i<Arreglo.length-1;i++){ 
for(int j=0;j<Arreglo.length-i-1;j++){ 
if(Arreglo[j+1]<Arreglo[j]){ 
A=Arreglo[j+1]; 
Arreglo[j+1]=Arreglo[j]; Arreglo[j]=A; 
System.out.print("Elemento a buscar:" ); 
int elemento = Leer.nextInt(); 
System.out.println("dato"); 
for(int i=0;i<Arreglo.length;i++){ 
System.out.println(Arreglo[i]); 
int posicion = busquedaBinaria(Arreglo, elemento); 
if(posicion == -1)
System.out.println("\nElemento no encontrado"); 
else System.out.println("\nElemento " + elemento + " encontrado en la posicion " + posicion); 
}

No hay comentarios:

Publicar un comentario