mirror of
https://hub.njuu.cf/TheAlgorithms/C-Plus-Plus.git
synced 2023-10-11 13:05:55 +08:00
document interpolation search 2
This commit is contained in:
parent
85020eea5f
commit
4bc199ff1d
@ -1,4 +1,17 @@
|
|||||||
|
/**
|
||||||
|
* \file
|
||||||
|
* \brief [Interpolation
|
||||||
|
* search](https://en.wikipedia.org/wiki/Interpolation_search) algorithm
|
||||||
|
*/
|
||||||
#include <iostream>
|
#include <iostream>
|
||||||
|
|
||||||
|
/** function to search the value in an array using interpolation search
|
||||||
|
* \param [in] arr array to search in
|
||||||
|
* \param [in] value value to search for
|
||||||
|
* \param [in] len length of array
|
||||||
|
* \returns index where the value is found
|
||||||
|
* \returns -1 if not found
|
||||||
|
*/
|
||||||
int InterpolationSearch(int A[], int n, int x) {
|
int InterpolationSearch(int A[], int n, int x) {
|
||||||
int low = 0;
|
int low = 0;
|
||||||
int high = n - 1;
|
int high = n - 1;
|
||||||
@ -11,18 +24,21 @@ int InterpolationSearch(int A[], int n, int x) {
|
|||||||
else
|
else
|
||||||
low = mid + 1; // x lies after mid
|
low = mid + 1; // x lies after mid
|
||||||
}
|
}
|
||||||
|
|
||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** main function */
|
||||||
int main() {
|
int main() {
|
||||||
int A[] = {2, 4, 5, 7, 13, 14, 15, 23};
|
int A[] = {2, 4, 5, 7, 13, 14, 15, 23};
|
||||||
int x = 17;
|
int x = 17;
|
||||||
int index = InterpolationSearch(
|
|
||||||
A, 8, x); // passed array A inside the InterpolationSearch function
|
///< passed array A inside the InterpolationSearch function
|
||||||
if (index != -1)
|
int index = InterpolationSearch(A, 8, x);
|
||||||
std::cout << "Number " << x << " is at " << index;
|
if (index < 0)
|
||||||
|
std::cout << "Number " << x << " not found" << std::endl;
|
||||||
else
|
else
|
||||||
std::cout << "Number " << x << " not found";
|
std::cout << "Number " << x << " is at " << index << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
// randomly set x bcoz array was defined by us , therefore not reasonable for
|
// randomly set x bcoz array was defined by us , therefore not reasonable for
|
||||||
|
Loading…
Reference in New Issue
Block a user