views:

474

answers:

2

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();
        }
    }
}
A: 
import java.util.Scanner;
import java.util.Arrays;
public class tester
{
    public static void main(String[] args)
    {
     int randomNums[];
     Scanner myScanner = new Scanner(System.in);
     int len = myScanner.nextInt();

     //create the array with length determined from input
     randomNums = new int[len];

     //populates the array with random numbers
     for(int y=0;y<len;y++)
     {
      randomNums[y] = (int)(Math.random()*50+1);
      System.out.println(randomNums[y]);
     }

     Arrays.sort(randomNums);
     int index=0;
     while(true)
     {
      int searchFor = myScanner.nextInt();
      //input of -1 will end search
      if (searchFor==-1)
       break;
      else
      {
        index = rBinarySearch(randomNums,0,len,searchFor); 
      }
      if (index==-1)
       System.out.println("not found");
      else
       System.out.println("the element was found at index: " + index);
     }
    }

    public static int rBinarySearch(int[] sorted, int first, int upto, int key) {

        if (first < upto) {
            int mid = first + (upto - first) / 2;  // Compute mid point.
            if (key < sorted[mid]) {
                return rBinarySearch(sorted, first, mid, key);

            } else if (key > sorted[mid]) {
                return rBinarySearch(sorted, mid+1, upto , key);

            } else {
                return mid;   // Found it.
            }
        }
        return -(first + 1);  // Failed to find key
    }
}
zPesk
+3  A: 

For a start, here is the original ArregloBinario class with the spacing fixed up:

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);
    }
}

And here's a recursive version:

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);
    }

    private int recursive (int elem, int inf, int sup, int med) {
        System.out.print(elementosRestantes(inf,sup));

        for (int i = 0; i<med; i++)
            System.out.print("   ");
        System.out.println(" * ");

        if (inf > sup)
            return -1;

        if (elem == datos[med])
            return med;

        if (elem<datos[med])
            return recursive (elem,inf,med-1,(inf + med) / 2);

    return recursive (elem,med+1,sup,(med + sup + 2) / 2);
    }

    public int busquedaBinaria(int elementoBusqueda)
    {
        int inf = 0;
        int sup = datos.length-1;
        int med = (inf + sup + 1 ) / 2;
        int ubi = -1;

        return recursive (elementoBusqueda,inf,sup,med);
    }

    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);
    }
}

Here's a sample run under Eclipse as the intensive testing it underwent :-)

Please write the number of elements in the array.
20
14 18 19 20 22 31 43 50 55 58 58 59 62 71 72 74 85 92 95 98 

Write a value (-1) to go out: 95
14 18 19 20 22 31 43 50 55 58 58 59 62 71 72 74 85 92 95 98 
                               * 
                                 59 62 71 72 74 85 92 95 98 
                                              * 
                                                85 92 95 98 
                                                       * 
The value 95 was found in position 18.

Write a number (-1 to go out): -1
paxdiablo