document interpolation search

This commit is contained in:
Krishna Vedala 2020-05-28 20:31:41 -04:00
parent d9ffc8aca1
commit 7fd12991f7
No known key found for this signature in database
GPG Key ID: BA19ACF8FC8792F7

View File

@ -1,36 +1,61 @@
#include<iostream> /**
* \file
* \brief [Interpolation
* search](https://en.wikipedia.org/wiki/Interpolation_search) algorithm
*/
#include <iostream>
// function to search the value in an array using interpolation search /** function to search the value in an array using interpolation search
int search(int arr[], int value, int len) { * \param [in] arr array to search in
int low = 0, high, mid; * \param [in] value value to search for
high = len-1; * \param [in] len length of array
while (arr[low] <= value && arr[high] >= value) { * \returns index where the value is found
mid = (low + ((value-arr[low])*(high-low)) / (arr[high]-arr[low])); * \returns 0 if not found
if (arr[mid] > value) */
high = mid-1; int interpolation_search(int arr[], int value, int len) {
else if (arr[mid] < value) int low = 0, high, mid;
low = mid+1; high = len - 1;
else
return mid; while (arr[low] <= value && arr[high] >= value) {
} mid = (low +
if (arr[low] == value) ((value - arr[low]) * (high - low)) / (arr[high] - arr[low]));
return low; if (arr[mid] > value)
return 0; high = mid - 1;
else if (arr[mid] < value)
low = mid + 1;
else
return mid;
}
if (arr[low] == value)
return low;
return 0;
} }
/** main function */
int main() { int main() {
int n, value, array[100], re; int n, value, re;
std::cout << "Enter the size of array(less than 100) : ";
std::cin >> n; std::cout << "Enter the size of array(less than 100) : ";
std::cout << "array in ascending (increasing) order : " << std::endl; std::cin >> n;
for (int i=0; i < n; i++)
std::cin >> array[i]; int *array = new int[n];
std::cout << "Enter the value you want to search : ";
std::cin >> value; std::cout << "array in ascending (increasing) order : " << std::endl;
re = search(array, value, n);
if (re == 0) for (int i = 0; i < n; i++) std::cin >> array[i];
std::cout << "Entered value is not in the array" << std::endl;
else std::cout << "Enter the value you want to search : ";
std::cout << "The value is at the position " << re << std::endl; std::cin >> value;
return 0;
} re = interpolation_search(array, value, n);
if (re == 0)
std::cout << "Entered value is not in the array" << std::endl;
else
std::cout << "The value is at the position " << re << std::endl;
delete[] array;
return 0;
}