1. 程式人生 > >JavaSE8基礎 經典二分查找問題 折半查找

JavaSE8基礎 經典二分查找問題 折半查找

技術分享 sorted while int end num pos div ret 折半查找

question:

技術分享

code:

public class Solution {
    /**
     * @param nums: An integer array sorted in ascending order
     * @param target: An integer
     * @return an integer
     */
    public int findPosition(int[] nums, int target) {
        // Write your code here
        int start = 0;
        int end = nums.length - 1;
        int mid = 0;
        
		while(start <= end) {
		    
			mid = (start + end) / 2;
			
			if(target < nums[mid]) {
				end = mid - 1;
			} else if(target > nums[mid]) {
				start = mid + 1; 
			} else {
				return mid;
			}
		}
		
		return -1;
    }
}

result:

技術分享

JavaSE8基礎 經典二分查找問題 折半查找