2025-01-18 插值查找法

This commit is contained in:
liangjinglin 2025-01-19 14:17:42 +08:00
parent 4c54be5bfc
commit 7a02e2ae09

View File

@ -0,0 +1,47 @@
package Search;
import SortAlgori.MergeSort;
public class InsertSearch {
private int[] arr;
public InsertSearch(int[] arr){
this.arr = arr;
}
private int search(int left, int right, int value){
int index = -1;
if(left >= right || arr[left] > value || arr[right] < value){
if(arr[left] == value){
return left;
}
return index;
}
int mid = left + (right - left)*(value - arr[left])/(arr[right] - arr[left]);
if(value == arr[mid]){
return mid;
}
if(value > arr[mid]){
index = search(mid + 1, right, value);
}
if(value < arr[mid]){
index = search(left, mid - 1, value);
}
return index;
}
public static void main(String[] args) {
int[] arr = new int[]{1,9,11,34,89,23,53,124,52};
MergeSort mergeSort = new MergeSort(arr);
mergeSort.mergeSort(0, arr.length-1);
System.out.println("排序后的序列:");
mergeSort.show();
InsertSearch insertSearch = new InsertSearch(mergeSort.getArr());
long startTime = System.currentTimeMillis();
int search = insertSearch.search(0, arr.length-1, 124);
long endTime = System.currentTimeMillis();
System.out.println("查找到的下标是:" + search);
System.out.println("查找所花费的时间:" + (endTime - startTime) + "ms");
}
}