Did I code this problem correctly? here is my outcome
In the searchRecursive method. in the searchRecusrsive method I am trying to check the element in the middle position , if the target is greater than the element in the middle position,recursively search for the second half of the array. if the target is less than the element in the middle position, recursively search the first half.
The first base case returns false if the low index exceeds the high index. the second base case returns true if the target is in the middle position.
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;
}
}