我需要一些帮助才能在数组中找到一个整数。数组必须是非排序的,并且算法必须递归完成。我的同事和我想出了将阵列切成两半的解决方案,检查中间数字是否是我们正在寻找的值,如果不是,它会将自身切成两半并不断重复,直到它转移到其他部分数组并最终停止。到目前为止,我一直在试验我的代码,就在这里。我想知道这出错的地方,我该如何改进它或让它完全发挥作用?谢谢
import java.util.*;
public class BinarySearch {
public static int search(int[] a, int low, int high, int value, int count)
{
int mid = (low + high) / 2;
if(a[mid] == value)
{
return mid;
}
if(a[mid] < value)
{
count = a[mid];
if(a[count] != value)
{
count--;
return search(a, mid + 1, high, value, count);
}
}
else
{
count = a[mid];
if(a[count] != value){
count++;
return search(a, low, mid - 1, value, count);
}
}
return low;
}
public static void main(String[] args)
{
BinarySearch BS = new BinarySearch();
int[] a = {5, 7, 1, 2, 4, 12, 9, 8, 89};
int value = 9;
int result = BS.search(a, 0, 0, value, 0);
if(result == -1)
{
System.out.print("the Value is not in the array!" );
}
else
{
System.out.print("the Value is in the array!" );
}
}
}