差值查找(二分查找的高级版)

package com.atguigu.Search;

import java.util.Arrays;

/**
 * 差值查找
 */
public class InsertValSearch {
    public static void main(String[] args) {
        int[] arr = new int[100];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = i + 1;
        }
//        System.out.println(Arrays.toString(arr));
        int arrIndex = insertValueSearch(arr,0,arr.length - 1,66);
        System.out.println("查找的下标为" + arrIndex);
    }

    private static int insertValueSearch(int[] arr, int left, int right, int findVal) {
        System.out.println("差值查找的次数~~");
        if (left > right || findVal < arr[left] || findVal > arr[right]){
            return -1;
        }
        int mid = left + (right - left)*(findVal - arr[left])/(arr[right] - arr[left]);
        int midVal = arr[mid];
        if (findVal > midVal){
            return insertValueSearch(arr,mid + 1,right,findVal);
        }else if (findVal < midVal){
            return insertValueSearch(arr,left,mid - 1,findVal);
        }else {
            return mid;
        }
    }
}

上一篇:二分查找详解


下一篇:数据结构与算法 -->> 查找算法