Binary Search Using Java (simple algo)


  • 0
    C
    public int search(int[] nums, int target) {
    
        if(nums.length == 0){
            return -1;
        }
        
        int low =0;
        int modifier = nums.length;
        int high = nums.length-1;
        
        for(int i=0; i<nums.length-1; i++){
            if(nums[i]>nums[i+1] ){
                modifier = i+1;
                break;
            }
        }
        
        if(target >= nums[0] )
            return findBinary(nums, target, low,  modifier -1);
        
        return findBinary(nums, target, modifier, high);
        
    }
    
    public static int findBinary(int[] nums, int target, int low, int high){
        while(low<=high){
            
            int mid =(low+high)/2;
            
            if(target < nums[mid]){
                high = mid-1;
            } else
            if(target > nums[mid]){
                low = mid + 1;
            } else{
                return mid;
            }
            
        }
        
        return -1;
    }
    

    Basically identifying in which sorted array (first or second) the number exists and executing the binary search on that part.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.