So basically what I want to do is a program that asks the user how big he wants his array to be and for the user to introduce the values inside the array. Then I want the user to be able to introduce a number and for the program to determine in which array the number is or determine that it doesn't exist. The following program currently generates the values of the arrays randomly and the user introduces how many array elements he wants to use. But I don't know how to make this in to what I previously explained.
package laboratorio9;
import java.util.Random;
import java.util.Arrays;
public class ArregloBinario
{
private int[] datos;
private static Random generador = new Random();
public ArregloBinario (int tamanio)
{
datos = new int[tamanio];
for (int i=0; i<tamanio; i++)
datos[i] = 10 + generador.nextInt(90);
Arrays.sort(datos);
}
public int busquedaBinaria(int elementoBusqueda)
{
int inferior = 0;
int superior = datos.length-1;
int medio = (inferior + superior + 1 ) / 2;
int ubicacion = -1;
// **HOW CAN I CHANGE THE FOLLOWING NTO A RECURSIVE FUNCTION>**
do
{
System.out.print(elementosRestantes(inferior,superior));
for (int i = 0; i<medio; i++)
System.out.print(" ");
System.out.println(" * ");
if (elementoBusqueda == datos[medio])
ubicacion=medio;
else if (elementoBusqueda<datos[medio])
superior = medio-1;
else
inferior = medio+1;
medio = (inferior + superior + 1) / 2;
} while ((inferior <=superior) && (ubicacion == -1));
return ubicacion;
}
public String elementosRestantes(int inferior, int superior)
{
StringBuilder temporal = new StringBuilder();
for (int i = 0; i < inferior; i++)
temporal.append( " " );
for (int i = inferior; i <= superior; i++)
temporal.append( datos[i] + " ");
temporal.append("\n");
return temporal.toString();
}
public String toString()
{
return elementosRestantes(0, datos.length-1);
}
}
// MAIN CLASS //
package laboratorio9;
import java.util.Scanner;
public class PruebaBusquedaBinaria {
public static void main(String[] args)
{
Scanner entrada = new Scanner(System.in);
int enteroABuscar;
int posicion;
System.out.println("Please write the number of elements in the array.");
int number = entrada.nextInt();
ArregloBinario arregloBusqueda = new ArregloBinario(number);
System.out.println(arregloBusqueda);
System.out.print("Write a value (-1) to go out: ");
enteroABuscar = entrada.nextInt();
System.out.println();
while (enteroABuscar != -1)
{
posicion = arregloBusqueda.busquedaBinaria(enteroABuscar);
if (posicion==-1)
System.out.println("The value " + enteroABuscar + " was not found.\n");
else
System.out.println("The value " + enteroABuscar +
" was found in position " + posicion + ".\n");
System.out.print(
"Write a number (-1 to go out): ");
enteroABuscar = entrada.nextInt();
System.out.println();
}
}
}