ARTICLE AD BOX
I am using java, and I am writing an algorithm that uses binary search in a recursive function.
The method declaration looks like this: public static int[] binarySearch(int[] nums, int key). The method has only two arguments: int[] nums (the array being searched), and int key (the item the method is looking for).
The method should return an integer array consisting of the first occurence of the key in the array and the index the key's last occurence ([first occurence, last occurence]).
The program should also consider an array like this [1,2,2,2,3] If the key is 2, then the program will have to go in both directions to find the starting and ending index of 2.
The following code is unfinished.
public static int[] binarySearch(int[] nums, int key){ int left = 0; int right = nums.length()-1; if(nums[left] > key || nums[right] < key){ return [-1,-1]; } if(left<right){ int start = right; //start at beginning int end = left; //start at end left = ((right-left)/2)+1; int[] sub = Arrays.copyOfRange(nums, left, right); int mid = (right-left)/2; if(sub[mid] == key) } }