Skip to content

Latest commit

 

History

History
33 lines (29 loc) · 726 Bytes

bs_template.md

File metadata and controls

33 lines (29 loc) · 726 Bytes

binary-search-template

public class Solution{
    public int binarySearch(int[] nums, int target){
        if(nums == null && nums.length == 0)return -1;
        
        int start = 0;
        int end = nums.length - 1;
        int mid;
        
        while(start + 1 < end){
            mid = start + (end - start) / 2;
            if(nums[mid] > target){
                end = mid;
            }else if(nums[mid] < target){
                start = mid;
            }else{
                end = mid;
            }
        }
        
        if(nums[start] == target){
            return start;
        }
        if(nums[end] == target){
            return end;
        }
        
        return -1;
    }
}