I have a major headache.
I am performing a search within an array and I want it to indicate the position of the element within the array, so far so good.
In fact, the code does not present errors at a glance, but when using it, everything jumps red red.
My code consists of two classes (main and search) inside a package called arrays, to put you in a situation.
The search code :
package busqueda;
public class busqueda {
public int buscar(int numeros[], int n) {
int principio, fin, centro;
principio = 0;
centro = numeros.length / 2;
fin = numeros.length - 1;
boolean encontrado = false;
while (principio <= fin || !encontrado) {
if (numeros[centro] == n) {
encontrado = true;
} else if (numeros[centro] < n) {
centro = -1;
} else {
centro = +1;
}
}
if (encontrado) {
return centro;
}
return 0;
}
}
And now the Main code :
package busqueda;
import busqueda.busqueda;
import java.util.*;
public class main {
public static void main(String[] args) {
Scanner teclado = new Scanner(System.in);
busqueda busca = new busqueda();
int numeros[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int pos = busca.buscar(numeros, 8);
if (pos > -1) {
System.out.println("Encontrado en la posicion: " + pos);
} else {
System.out.println("Error");
}
}
}
Everything seems to be well planned, but when executing the exercise I get the following:
I imagine that the problem is in the search class , but I can't see it, I hope someone can help me.
The algorithm that appears in the code shown is not recursive , but rather iterative ; a recursive algorithm must include calls to itself.
recursive algorithm
If the function
buscar
represents a binary search algorithm in its recursive variant, the code should look similar to the following:iterative algorithm
If, on the other hand, the title of the question is incorrect and you want to use the iterative variant included in the body of the question, the code should be similar to the following:
Already existing algorithm
Beyond a possible hobbies or algorithmic exercise, it would be much more appropriate to use the version already incorporated in the standard library of the Java programming language:
For more information, see
Arrays.binarySearch(int[], int)
the Java documentation.