Java BinarySearch

前端 未结 10 2146
忘了有多久
忘了有多久 2020-12-09 23:33

Can I get some help please? I have tried many methods to get this to work i got the array sorted and to print but after that my binary search function doesnt want to run and

10条回答
  •  眼角桃花
    2020-12-09 23:57

    I somehow find the iterative version not quite easy to read, recursion makes it nice and easy :-)

    public class BinarySearch {
    
        private static int binarySearchMain(int key, int[] arr, int start, int end) {
            int middle = (end-start+1)/2 + start; //get index of the middle element of a particular array portion
    
            if (arr[middle] == key) {
                return middle;
            }
    
            if (key < arr[middle] && middle > 0) {
                return binarySearchMain(key, arr, start, middle-1); //recurse lower half
            }
    
            if (key > arr[middle] && middle < arr.length-1) {
                return binarySearchMain(key, arr, middle+1, end); //recurse higher half
            }
    
            return Integer.MAX_VALUE; 
        }
    
        public static int binarySearch(int key, int[] arr) { //entry point here
            return binarySearchMain(key, arr, 0, arr.length-1);
        }
    
    }
    

提交回复
热议问题