[关闭]
@xmruibi 2015-04-28T13:48:02.000000Z 字数 760 阅读 651

Search Problem

Algorithm


Search Problems can be divided as Sequential Search, Binary Search, Interpolation


Please Check:


Interpolation Equation:

index=(targetarr[low])(arr[high]arr[low])(highlow)

On average the interpolation search makes about log(log(n)) comparisons (if the elements are uniformly distributed), where n is the number of elements to be searched. In the worst case (for instance where the numerical values of the keys increase exponentially) it can make up to O(n) comparisons.

  1. public int interpolationSearch(int[] nums, int key) {
  2. int l = 0, r = nums.length-1;
  3. while(l<r){
  4. int m = l+(r-l)*(key - nums[l])/(nums[r]-nums[l]);
  5. if(nums[m]<key)
  6. l = m+1;
  7. else if(nums[m]>key)
  8. r = m;
  9. else
  10. return m;
  11. }
  12. return -1;
  13. }

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注