我编写了一个二进制搜索算法,它工作正常,但是当有重复项时它不能正常工作,或者数组中的数字2或更多数字数字它返回数组中找不到的值。我该怎么做才能解决这个问题,我是否需要在数组中搜索任何重复项来处理重复项? 或者我可以阻止随机数生成器生成重复项吗?
以下是代码:
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;
}
Arrays.sort(arr);
for (int i = 0; i < arr.length; i++)
System.out.println("Number is: " + arr[i]);
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) {
if (LowIndex <= HighIndex) {
int MidIndex = (LowIndex + HighIndex)/2;
if (array[MidIndex] == Target){
System.out.println("Found target value at index " + MidIndex);
return Target;}
else if (array[MidIndex] > Target)
return binarySearch(LowIndex, MidIndex-1, Target, array);
else
return binarySearch(MidIndex+1, HighIndex, Target, array);
}
System.out.println("target value not found");
return -1;
}
}
感谢您的帮助。
答案 0 :(得分:2)
第一次拨打binarySearch
时,请按以下方式拨打电话:
binarySearch(arr[0], arr.length-1, LookFor, arr);
将其更改为
binarySearch(0, arr.length-1, LookFor, arr);