我已经编写了一个二进制搜索程序作为项目的一部分。它会编译并运行,但是当它到达程序的一部分时,它应该在数组中搜索目标值(由用户输入),它什么也没做,它只是让我输入一个目标值,但似乎没有搜索或终止。
这是我的代码:
/**
*
*/
package ProofOfConcepts;
import java.util.Random;
import java.util.Scanner;
/**
* @author Kirome
*
*/
public class BinarySearch {
static int RandomNum;
static int NumSize;
static int[] arr;
static int rangeOfNum;
static int LookFor;
static Random numGen = new Random();
static Scanner Input = new Scanner(System.in);
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter the size of the data set");
NumSize = Input.nextInt();
System.out.println("Enter the range of the random numbers");
rangeOfNum = Input.nextInt();
arr = new int[NumSize];
for (int i = 0; i <= NumSize-1; i++) {
RandomNum = numGen.nextInt(rangeOfNum);
arr[i] = RandomNum;
System.out.println("Number is: " + RandomNum);
}
System.out.println("Enter number you want to search for: ");
LookFor = Input.nextInt();
binarySearch(arr[0], arr.length-1, LookFor, arr);
}
//Binary Search Algorithm
public static int binarySearch(int LowIndex, int HighIndex, int Target, int[] array) {
int MidIndex = (LowIndex + HighIndex)/2;
while (LowIndex <= HighIndex) {
if (array[MidIndex] == Target){
System.out.println("Target is found at: " + array[MidIndex]);
if (array[MidIndex] < Target){
binarySearch(LowIndex, MidIndex-1, Target, array);
}
if (array[MidIndex] > Target){
binarySearch(MidIndex+1, HighIndex, Target, array);
} else {
System.out.println("Target number is not in the array");
}
}
}
System.out.println(array);
return Target;
}
}
它令人沮丧,因为我知道它为什么不能正常运行一定很简单。在此先感谢,并且 ps 我不是最好的程序员。