Как создать цикл, который реализует рекурсивный бинарный поиск для поиска n чисел в массиве? ДЖАВА - PullRequest
0 голосов
/ 06 марта 2019

Мой код печатает только одно число, как я могу создать цикл для поиска n чисел?

package binariarecursiva;

import java.util.Scanner; / ** * * @author Пользователь * / открытый класс BinariaRecursiva {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) 
{

  int[] array = {1, 3, 5, 6, 8, 12, 19, 21, 27, 31, 35, 45, 80, 81, 82, 85, 87, 89, 95, 101, 200, 501, 707, 1000};
  Scanner teclado = new Scanner(System.in);
  int n = teclado.nextInt();
  int x = teclado.nextInt();
  int esquerda = 0;
  int direita = array.length-1;
  System.out.println(buscaBinaria(array,  esquerda,  direita, x, n));
}

public static int buscaBinaria (int[] array, int esquerda, int direita, int x, int n)
{
    int meio = (esquerda + direita)/2; 
    if(direita < esquerda)
    {
        return -1; 
    }

    if(x==array[meio])
    {
        return meio; 
    }
    else if(x<array[meio])
    {
       return buscaBinaria(array, esquerda, meio - 1, x);
    }
    else
    {
        return buscaBinaria(array, meio + 1, direita, x);          
    }
}

}

1 Ответ

0 голосов
/ 06 марта 2019

Вам просто нужно немного изменить свой метод main(). Сначала вы читаете значение n из пользовательского ввода, как вы уже сделали. Затем вы выполняете цикл n раз, и на каждой итерации вы спрашиваете пользователя, какое значение он хотел бы найти.

public static void main(String[] args)
{
    int[] array = {1, 3, 5, 6, 8, 12, 19, 21, 27, 31, 35, 45, 80, 81, 82, 85, 87, 89, 95, 101, 200, 501, 707, 1000};
    Scanner teclado = new Scanner(System.in);
    System.out.print("Enter number of runs: ");
    int n = teclado.nextInt();
    int esquerda = 0;
    int direita = array.length-1;
    for(int i = 0; i < n; i++) {
        System.out.print("Enter number to search for: ");
        int x = teclado.nextInt();
        System.out.println(buscaBinaria(array, esquerda, direita, x));
    }
}

Также измените сигнатуру buscaBinaria(), в качестве параметра не требуется n.

Полный код

package binariarecursiva;
import java.util.Scanner;

public class BinariaRecursiva {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {

        int[] array = {1, 3, 5, 6, 8, 12, 19, 21, 27, 31, 35, 45, 80, 81, 82, 85, 87, 89, 95, 101, 200, 501, 707, 1000};
        Scanner teclado = new Scanner(System.in);
        System.out.print("Enter number of runs: ");
        int n = teclado.nextInt();
        int esquerda = 0;
        int direita = array.length-1;
        for(int i = 0; i < n; i++) {
            System.out.print("Enter number to search for: ");
            int x = teclado.nextInt();
            System.out.println(buscaBinaria(array, esquerda, direita, x));
        }
    }

    public static int buscaBinaria (int[] array, int esquerda, int direita, int x)
    {
        int meio = (esquerda + direita)/2;
        if(direita < esquerda)
        {
            return -1;
        }

        if(x==array[meio])
        {
            return meio;
        }
        else if(x<array[meio])
        {
            return buscaBinaria(array, esquerda, meio - 1, x);
        }
        else
        {
            return buscaBinaria(array, meio + 1, direita, x);
        }
    }
}
...