code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

Binarysearchrecursive

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

class BinarySearchRecursive {

  static int func(int[] nums, int start, int end, int target){
    if(start > end) {
      return -1;
    }
    int mid = Math.abs((start+end)/2);
    if(nums[mid] == target){
      return mid;
    }
    if(nums[mid] > target) {
      return func(nums, start, mid - 1, target);
    } else {
      return func(nums, mid + 1, end, target);
    }
  }

  public static void main(String[] args){
    int[] nums = new int[]{1,4,6,23,67,78,93,123,646,5687};
    int result = func(nums, 0, nums.length, 646);
    System.out.println(result);
  }
}

Created 2021-12-21T03:41:59+00:00 · Edit