Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.95 KB | None | 0 0
  1. /**
  2. Algoritmo de búsqueda binaria secuencial en Java
  3. @author parzibyte
  4. @web parzibyte.me/blog
  5. */
  6. public static int busquedaBinariaConWhile(int[] arreglo, int busqueda){
  7. int izquierda = 0, derecha = arreglo.length - 1;
  8.  
  9. while(izquierda <= derecha){
  10. // Calculamos las mitades...
  11. int indiceDelElementoDelMedio = (int) Math.floor((izquierda + derecha) / 2);
  12. int elementoDelMedio = arreglo[indiceDelElementoDelMedio];
  13.  
  14. // Ver si está en la mitad y romper aquí el ciclo
  15. if(elementoDelMedio == busqueda){
  16. return indiceDelElementoDelMedio;
  17. }
  18. // Si no, entonces vemos si está a la izquierda o derecha
  19.  
  20. if(busqueda < elementoDelMedio){
  21. derecha = indiceDelElementoDelMedio - 1;
  22. }else{
  23. izquierda = indiceDelElementoDelMedio + 1;
  24. }
  25. }
  26. // Si no se rompió el ciclo ni se regresó el índice, entonces el elemento no existe
  27. return -1;
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement