Skip to content

Instantly share code, notes, and snippets.

@HaoyangFan
Created November 13, 2018 06:32
Show Gist options
  • Select an option

  • Save HaoyangFan/c83c471119afa478ed27e46de0accfee to your computer and use it in GitHub Desktop.

Select an option

Save HaoyangFan/c83c471119afa478ed27e46de0accfee to your computer and use it in GitHub Desktop.
A simple implementation of recursive binary search in Java.
/**
* A simple implementation of recursive binary search in Java.
*
* @author Haoyang Fan
* @since 11-12-2018
*/
public class RecursiveBinarySearch {
/**
* @param nums an integer array sorted in ascendin order
* @param target an integer to find
* @return an integer
*/
public int findPosition(int[] nums, int target) {
return binarySearch(nums, 0, nums.length - 1, target);
}
private int binarySearch(int[] nums, int start, int end, int target) {
// base case: the target does not exist in the array
if (start > end) return -1;
// find the mid point of search range
int mid = (start + end) / 2;
if (nums[mid] == target) return mid;
if (nums[mid] < target) return binarySearch(nums, mid + 1, end, target);
return binarySearch(nums, start, mid - 1, target);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment