插值查找
阿新 • • 發佈:2018-08-31
span 一半 list param color integer ram turn args
一半對於二分查找來說 mid=(low+high)/2=low+(high-low)/2的位置,我們對這個1/2改進一下:mid=low+(high-low)*(key-datas[low])/(datas[high]-datas[low]),也就是將1/2改成了(key-datas[low])/(datas[high]-datas[low]),我們來看改進的二分查找:
1 package Search; 2 3 import java.util.ArrayList; 4 import java.util.List; 5 6 public class InterpolationSearch7 { 8 public static void main(String[] args) 9 { 10 int[] waitingArrats = new int[] { 0, 4, 5, 6, 15, 27, 36, 53, 69, 87, 88, 89, 90, 91 }; 11 List<Integer> Datas = new ArrayList<Integer>(); 12 for (int p : waitingArrats) 13 { 14 // Sort(Datas, p);// 向有序隊列添加新元 15 Datas.add(p); 16 } 17 int findindex = Find(Datas, 15); 18 if (findindex > 0) System.out.println("find index at:" + findindex); 19 else 20 System.out.println("not find index "); 21 /* 22 * for (int i : Datas) { System.out.println(i); }23 */ 24 } 25 26 /// <summary> 27 /// 28 /// </summary> 29 /// <param name="Datas"></param> 30 /// <param name="newvalue"></param> 31 // static void Sort(List<Integer> Datas, int newvalue) 32 static int Find(List<Integer> Datas, int newvalue) 33 { 34 int low = 0; 35 int high = Datas.size() - 1; 36 int mid = low + (newvalue - Datas.get(low)) / (Datas.get(high) - Datas.get(low)); // (low 37 // + 38 // high) 39 // / 40 // 2; 41 int index = -1; 42 /* 43 * if (Datas.size() == 0) { Datas.add(newvalue); return; } 44 */ 45 while (low <= high) 46 { 47 // if (newvalue <= Datas.get(mid)) 48 if (newvalue < Datas.get(mid)) 49 {// 新值在中間位左側 50 high = mid - 1; 51 } 52 // 新值在中間位右側 53 if (newvalue > Datas.get(mid)) 54 { 55 low = mid + 1; 56 } 57 mid = low + (newvalue - Datas.get(low)) / (Datas.get(high) - Datas.get(low));// (high 58 // + 59 // low) 60 // / 61 // 2; 62 /* 63 * if (high < low) // 當右指針越過中間位,大於左指針時停止 { index = high + 1;// 或者 64 * low Datas.add(index, newvalue); break; } 65 */ 66 67 if (newvalue == Datas.get(mid)) 68 { 69 70 return mid; 71 } 72 } 73 return -1; 74 } 75 }
對於關鍵字分布比較均勻的時候,插值查找算法的平均性能略好於折半查找,然而序列中出現類似於 {0,1,2,2000,2001,.......99999998,9999999} 這種極為不均勻的數據通常插值查找不是個好的選擇.
插值查找