package com.hao.firstdemo.datastruct.search;
/**
* @author haoxiansheng
* @data 2020/5/9 21:10
*/
public class InsertValueSearch {
public static void main(String[] args) {
int[] arr = new int[100];
for (int i = 0; i < 100; i++) {
arr[i] = i + 1;
}
int resIndex = insertValueSearch(arr, 0, arr.length - 1, 6);
System.out.println(resIndex);
}
/**
* @param arr 查找集合
* @param left 左索引
* @param right 右索引
* @param findValue 查找值
* @return 找到返回對應下標 沒有返回-1
*/
public static int insertValueSearch(int[] arr, int left, int right, int findValue) {
// 這幾個條件必須需要 後面的還可以起到優化作用
if (left > right || findValue < arr[0] || findValue > arr[arr.length - 1]) { // 說明遞歸整個數組還是沒有找到
return -1;
}
// 求mid
int mid = left + (right - left) * (findValue - arr[left]) / (arr[right] - arr[left]);
int midValue = arr[mid];
if (findValue > midValue) { // 說明要向右遞歸查找
return insertValueSearch(arr, mid + 1, right, findValue);
} else if (findValue < midValue) { // 說明向左遞歸
return insertValueSearch(arr, left, mid - 1, findValue);
} else {
return mid;
}
}
}