插值查找和斐波拉契查找
作者:互联网
插值查找
package com.dai.search; import java.util.Arrays; 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 index = insertValueSearch(arr, 0, arr.length-1, 51); System.out.println("index=" + index); //System.out.println(Arrays.toString(arr)); } /** * * @param arr : 数组 * @param left :左索引 * @param right:右索引 * @param findVal :待查找的值 * @return : 返回下标 */ public static int insertValueSearch(int[] arr, int left, int right, int findVal) { if(left>right || findVal<arr[left] || findVal>arr[right]) { return -1; } // 插值查找只有此处mid取值与二分查找不同 int mid = left + (findVal-arr[left])/(arr[right]-arr[left])*(right-left); if(findVal<arr[mid]) { return insertValueSearch(arr, left, mid-1, findVal); }else if(findVal > arr[mid]) { return insertValueSearch(arr, mid+1, right, findVal); }else { return mid; } } }
斐波拉契查找
package com.dai.search; import java.util.Arrays; public class FibonacciSearch { public static int maxsize = 20; public static void main(String[] args) { int[] arr = {1,3,4,56,89,100,145,456,1000,1234}; //System.out.println(Arrays.toString(fib())); int index = fibSearch(arr, 1234); System.out.println(index); } //生成斐波那契数列 public static int[] fib() { int[] f = new int[maxsize]; f[0] = 1; f[1] = 1; for(int i=2;i<maxsize; i++) { f[i] = f[i-1] + f[i-2]; } return f; } public static int fibSearch(int[] arr, int key) { int[] f = fib(); int low = 0; int high = arr.length-1; int mid = 0; int k = 0; while(high > f[k]-1) { k++; } int[] temp = Arrays.copyOf(arr, f[k]); for(int i=high+1;i<f[k]-1;i++) { temp[i] = arr[high]; } while(low <= high) { mid = low + f[k-1] - 1; if(key>temp[mid]) { k-=2; low = mid +1; } if(key<temp[mid]) { k-=1; high = mid -1; } if(key==temp[mid]) { if(mid<=high) return mid; else { return high; } } } return -1; } }
标签:arr,right,int,波拉,mid,查找,和斐,public 来源: https://www.cnblogs.com/shengtudai/p/14426893.html