Record interview in binary search algorithm problem

To summarize an algorithm for this problem two faces, the code was written half, found himself logic seems to have problems, then there is no way to write down, leading ultimately did not do it out of the interview Baidu a moment, and instantly feel .. .......

Ado, look directly title

Requirements: write a binary search, using an iterative way to achieve, and the algorithm design test cases

After the interview see this topic is really simple and straightforward to write code from

public class Algorithm{
    public int binarySearch(int[] nums,int target){
        int left = 0;
        int right = nums.length-1;
        while(left<=right){
            int mid =(left+right)/2;
            if(nums[mid]==target){
                return mid;
            }
            else if(nums[mid]<target){
                left = mid +1;
            }
            else if(nums[mid]>target){
                right = mid-1;
            }
        }
        return -1;
    }
}

Test Case:

public class AlgorithmTestcase{
    public static void main(String[] args){
        Algorithm algorithm = new Algorithm();
        int [] nums = {1,3,5,7,8,9};
        int target = 7;
        System.out.println(algorithm.binarySearch(nums,target))
    }
}

Of course, I'm just here to write a positive test case, because I write dichotomy is above the target value if they can be found, it returns only goal of the index index, if the target is not found in nums if the collection is returned -1 this case the reader to write their own.

Guess you like

Origin www.cnblogs.com/igubai/p/12127600.html