Advertisement
kartikkukreja

Interpolation Search

Aug 17th, 2013
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. #include <cstdio>
  2. #include <cstdlib>
  3. #include <algorithm>
  4. #include <vector>
  5. #include <deque>
  6. using namespace std;
  7.  
  8. /*
  9.  * Searches for @value in [@first, @last) with linear interpolation of values
  10.  * and returns an iterator i in [@first, @last) s.t. *i == @value
  11.  * Returns @last if @value is not found in the range
  12.  * T must have definitions for these operators: -, <, ==
  13.  */
  14. template<class RandomAccessIterator, class T>
  15. RandomAccessIterator interpolation_search(RandomAccessIterator first,
  16.                                           RandomAccessIterator last,
  17.                                           const T& value) {
  18.     RandomAccessIterator middle, not_found = last;
  19.     last -= 1;
  20.     T* lo = &(*first);
  21.     T* hi = &(*last);
  22.     T* mid;
  23.  
  24.     if (value < *lo)
  25.         return not_found;
  26.     if (!(value < *hi))
  27.         first = last;
  28.  
  29.     while (first < last)  {
  30.         middle = first + ((last - first) * (value - *lo)) / (*hi - *lo);
  31.         mid = &(*middle);
  32.         if (*mid < value)    {
  33.             first = middle + 1;
  34.             lo = mid;
  35.         } else if (value < *mid)    {
  36.             last = middle - 1;
  37.             hi = mid;
  38.         } else
  39.             return middle;
  40.     }
  41.     return (value == *first) ? first : not_found;
  42. }
  43.  
  44. int main()  {
  45.     int A[] = {0, 0, 2, 2, 2}, N = 5;
  46.  
  47.     int *result = interpolation_search(&A[0], &A[N], 2);
  48.     if (result == &A[N])
  49.         printf("Not found\n");
  50.     else
  51.         printf("Found at position: %d\n", result - A);
  52.  
  53.     vector<int> vec(&A[0], &A[N]);
  54.  
  55.     vector<int>::iterator res = interpolation_search(vec.begin(), vec.end(), 1);
  56.     if (res == vec.end())
  57.         printf("Not found\n");
  58.     else
  59.         printf("Found at position: %d\n", res - vec.begin());
  60.  
  61.     deque<int> deck(&A[0], &A[N]);
  62.  
  63.     deque<int>::iterator r = interpolation_search(deck.begin(), deck.end(), 0);
  64.     if (r == deck.end())
  65.         printf("Not found\n");
  66.     else
  67.         printf("Found at position: %d\n", r - deck.begin());
  68.  
  69.     return 0;
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement