变量和二分查找差不多,但是公式变了
公式:
int mid = left + (right - left) * (indexValue -arr[left]) / ( arr[right] - arr[left])
注意事项:
适用于数据量比较大,数据分布均匀的数据
代码:
package search;
import java.util.ArrayList;
import java.util.List;
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {1,8,10,89,1000,1234,1234};
List<Integer> ls = binartSearch(arr, 0, arr.length - 1, 1234);
System.out.print(ls);
}
public static List<Integer> binartSearch(int[] arr, int left, int right, int findValue) {
if(left > right) {
System.out.print("没有找到!");
return null;
}
int mid = left + (right - left) * (findValue - arr[left])/(arr[right]-arr[left]);
if(arr[mid] > findValue) {
return binartSearch(arr, left, mid - 1, findValue);
}else if(arr[mid] < findValue) {
return binartSearch(arr, mid + 1, right, findValue);
}else {
List<Integer> resIndexList = new ArrayList<Integer>();
int temp = mid-1;
while(true) {
if(temp < 0 || arr[temp] != findValue) {
break;
}
resIndexList.add(temp);
temp--;
}
resIndexList.add(mid);
temp=mid+1;
while(true) {
if(temp > arr.length - 1 || arr[temp] != findValue) {
break;
}
resIndexList.add(temp);
temp++;
}
return resIndexList;
}
}
}