二分查找

二分查找,从已排序的数组中查找目标值的下标,找不到返回-1

每次折半,比中间值少从低位遍历,比中间值大从高位遍历,等于中间值返回mid下标。

中间值等于低位开始值,说明找不到,返回-1。

package com.test

import org.junit.jupiter.api.Test;

/**
 * @ClassName SolutionTest
 * @Description: TODO
 * @Author Administrator
 * @Date 2021/4/16 
 * @Version V1.0
 **/
public class SolutionTest {
public int binarySearch(int[] nums,int target, int low,int height) {
    if(low == height) {
        return nums[low] == target ? low : -1;
    }
    int mid = low + (height - low >> 1);
    if(nums[mid] == target) {
        return mid;
    }else if(nums[mid] > target) {
        return binarySearch(nums,target, low, mid-1);
    } else {
        return binarySearch(nums,target, mid+1, height);
    }
}
 @Test public void search() { int[] nums = new int[] {1,2,3,4,5,6,7,8}; int index = binarySearch(nums, 3, 0, nums.length-1); System.out.println(index); // 2 } }

 

posted @ 2021-04-16 17:51  fosonR  阅读(66)  评论(0编辑  收藏  举报