在searchRecursive方法中。在searchRecusrsive方法中,我试图检查中间位置的元素,如果目标大于中间位置的元素,则递归搜索数组的后半部分。如果目标小于中间位置的元素,则递归搜索前半部分。
如果低索引超过高索引,则第一个基本案例返回false。如果目标处于中间位置,则第二个基本案例返回true。
class SearchSortedArray
{
public static void main(String[] args)
{
int[] sorted = {10, 20, 30, 40};
System.out.println("***Iterative***");
for (int i = 0; i < sorted.length; i++)
{
System.out.println(sorted[i] + " found? " +
searchIterative(sorted[i], sorted));
System.out.println((sorted[i] + 1) + " found? " +
searchIterative(sorted[i] + 1, sorted));
}
System.out.println("***Recursive***");
for (int i = 0; i < sorted.length; i++)
{
System.out.println(sorted[i] + " found? " +
searchRecursive(sorted[i], sorted, 0, sorted.length - 1));
System.out.println((sorted[i] + 1) + " found? " +
searchRecursive(sorted[i] + 1, sorted, 0, sorted.length - 1));
}
}
private static boolean searchIterative(int target, int[] a)
{
int low = 0,
high = a.length - 1,
middle;
while (low <= high)
{
middle = (low + high) / 2;
if (target == a[middle])
return true;
if (target > a[middle])
low = middle + 1;
else
high = middle - 1;
}
return false;
}
private static boolean searchRecursive(int target, int[] a, int low, int high)
{
if (low > high) return false;
int middle;
middle = (low + high) / 2;
if (target == a[middle])
return true;
if (target < a[middle])
{
return searchRecursive(target, a, low, middle -1);
}
if (target > a[middle])
{
return searchRecursive(target, a, middle+1, high);
}
return false;
}
}