Created
March 3, 2019 03:23
-
-
Save graphoarty/22fd9a4fe8eb42e8d124cf8c86335a1e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cmath> | |
using namespace std; | |
int z = 0; | |
int interpolation(int arr[], int left, int right, int key){ | |
int low = left; | |
int high = right - 1; | |
int mid; | |
while (arr[high] != arr[low] && key >= arr[low] && key <= arr[high]) { | |
mid = low + ( (key - arr[low]) * (high - low) / (arr[high] - arr[low]) ); | |
if (key > arr[mid]){ | |
low = mid + 1; | |
} else if (key < arr[mid]){ | |
high = mid - 1; | |
} else{ | |
return mid; | |
} | |
} | |
if (key == arr[low]){ | |
return low ; | |
} else { | |
return -1; | |
} | |
} | |
int main() | |
{ | |
int L[] = {0, 1, 2, 3, 4, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610}; | |
//int L[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; | |
int left = 0; | |
int right = sizeof(L) / sizeof(L[0]); | |
int key = 144; | |
int x; | |
if((x = interpolation(L, left, right, key)) == -1 ){ | |
cout << "Key doesn't exist"<< endl; | |
} else { | |
cout << "The position of Key is " << x << endl; | |
} | |
return 0; } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment