package org.structure.search;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* 插值查找
* @author cjj_1
* @date 2020-08-18 11:35
*/
public class InterpolationSearch {
public static void main(String[] args) {
int[] arr = {1,34,34,89,90,100,101};
List<Integer> list = interpolationSerach(arr,0,arr.length-1,34,new ArrayList<Integer>());
System.out.println(Arrays.toString(list.toArray()) +":是下标!");
}
public static int interpolationSerach(int[] arr,int left,int right,int findval){
if(left>right || arr[left]>findval|| arr[right]<findval)
return -1;
int mid = left +(right -left) * (findval - arr[left])/(arr[right]-arr[left]);
int midvalue = arr[mid];
if(findval<midvalue){//左递归
return interpolationSerach(arr,left,mid-1,findval);
}else if(findval>midvalue){
return interpolationSerach(arr,mid+1,right,findval);
}else {
return mid;
}
}
public static List interpolationSerach(int[] arr, int left, int right, int findval, List<Integer> list){
if(left>=right|| arr[left]>findval|| arr[right]<findval)
return list;
int mid = left +(right -left) * (findval - arr[left])/(arr[right]-arr[left]);
if(mid<0)
return list;
int midvalue = arr[mid];
if(findval<midvalue){//左递归
interpolationSerach(arr,left,mid-1,findval,list);
}else if(findval>midvalue){
interpolationSerach(arr,mid+1,right,findval,list);
}else {
list.add(mid);
interpolationSerach(arr,left,mid-1,findval,list);
interpolationSerach(arr,mid+1,right,findval,list);
// return mid;
}
return list;
}
}
插值查找
最新推荐文章于 2024-06-28 14:32:57 发布