TizzyT

InterpolationSearch -TizzyT

Nov 11th, 2018
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.62 KB | None | 0 0
  1. // Variant of BinarySearch utilizing linear interpolation to narrow the location of the key instead of halving.
  2.  
  3. private static int InterpolationSearch(int[] arr, int value)
  4. {
  5.     if (arr.Length == 1) return 0;
  6.     int B = 0, T = arr.Length - 1;
  7.     int L = arr[B], H = arr[T];
  8.     if (L == value) return 0;
  9.     if (H == value) return T;
  10.     if (value < L || value > H) return -1;                      
  11.     while (T > B)
  12.     {
  13.         int idx = B + (int)((T - B) * ((float)(value - L) / (H - L)));
  14.         int val = arr[idx];
  15.         if (val > value) H = arr[T = idx - 1];
  16.         else if (val < value) L = arr[B = idx + 1];
  17.         else return idx;
  18.     }
  19.     return -1;
  20. }
Advertisement
Add Comment
Please, Sign In to add comment