Después de tanto batallar hemos dado con la contestación de este asunto que agunos lectores de esta web presentan. Si deseas compartir algún detalle puedes aportar tu conocimiento.
Ejemplo 1: búsqueda binaria java
// Java implementation of iterative Binary Search classBinarySearch// Returns index of x if it is present in arr[], // else return -1 intbinarySearch(int arr[],int x)int l =0, r = arr.length -1;while(l <= r)int m = l +(r - l)/2;// Check if x is present at mid if(arr[m]== x)return m;// If x greater, ignore left half if(arr[m]< x)
l = m +1;// If x is smaller, ignore right half else
r = m -1;// if we reach here, then element was // not present return-1;// Driver method to test above publicstaticvoidmain(String args[])BinarySearch ob =newBinarySearch();int arr[]=2,3,4,10,40;int n = arr.length;int x =10;int result = ob.binarySearch(arr, x);if(result ==-1)System.out.println("Element not present");elseSystem.out.println("Element found at "+"index "+ result);
Ejemplo 2: búsqueda binaria en java
importjava.util.Scanner;// Binary Search in JavaclassMainintbinarySearch(int array[],int element,int low,int high)// Repeat until the pointers low and high meet each otherwhile(low <= high)// get index of mid elementint mid = low +(high - low)/2;// if element to be searched is the mid elementif(array[mid]== element)return mid;// if element is less than mid element// search only the left side of midif(array[mid]< element)
low = mid +1;// if element is greater than mid element// search only the right side of midelse
high = mid -1;return-1;publicstaticvoidmain(String args[])// create an object of Main classMain obj =newMain();// create a sorted arrayint[] array =3,4,5,6,7,8,9;int n = array.length;// get input from user for element to be searchedScanner input =newScanner(System.in);System.out.println("Enter element to be searched:");// element to be searchedint element = input.nextInt();
input.close();// call the binary search method// pass arguments: array, element, index of first and last elementint result = obj.binarySearch(array, element,0, n -1);if(result ==-1)System.out.println("Not found");elseSystem.out.println("Element found at index "+ result);
Puntuaciones y comentarios
Al final de todo puedes encontrar las notas de otros desarrolladores, tú todavía eres capaz dejar el tuyo si te gusta.
¡Haz clic para puntuar esta entrada!
(Votos: 0 Promedio: 0)