class Solution {
// iterative
public int search(int[] nums, int target) {
// Corner case
if(nums == null || nums.length == 0) return -1;
int low = 0;
int high = nums.length-1;
while(low <= high){
int mid = (high-low)/2 + low;
if(nums[mid] == target) return mid;
if(nums[mid] < target) low = mid + 1;
else high = mid - 1;
}
return -1;
}
// Recursive
public static int Rsearch(int[] nums, int low, int high, int target){
if(low > high) return -1;
int mid = low + (high-low)/2;
if(target == nums[mid])
return mid;
else if(target < nums[mid])
return Rsearch(nums, low, mid-1, target);
else
return Rsearch(nums, mid+1, high, target);
}
}
A good blog to read about binary Search callicoder
Top comments (0)