Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions Search_algo/Interpolation_Search.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
/*
* C++ program to implement Interpolation Search.
*
* Interpolation Search is an improvement over Binary Search for instances
* where the values in a sorted array are uniformly distributed.
*/

#include <iostream>
#include <vector>

int interpolationSearch(const std::vector<int>& arr, int x) {
int n = arr.size();
if (n == 0) return -1;

int lo = 0, hi = (n - 1);

// Since array is sorted, an element present
// in array must be in range defined by corner
while (lo <= hi && x >= arr[lo] && x <= arr[hi]) {
if (lo == hi) {
if (arr[lo] == x) return lo;
return -1;
}

// Probing the position with keeping
// uniform distribution in mind.
// pos = lo + [ (x-arr[lo])*(hi-lo) / (arr[hi]-arr[lo]) ]
int pos = lo + (((double)(hi - lo) /
(arr[hi] - arr[lo])) * (x - arr[lo]));

// Condition of target found
if (arr[pos] == x)
return pos;

// If x is larger, x is in upper part
if (arr[pos] < x)
lo = pos + 1;
// If x is smaller, x is in lower part
else
hi = pos - 1;
}
return -1;
}

// Main function to test the algorithm
int main() {
std::vector<int> arr = {10, 12, 13, 16, 18, 19, 20, 21,
22, 23, 24, 33, 35, 42, 47};
int x = 18;

int index = interpolationSearch(arr, x);

if (index != -1) {
std::cout << "Number " << x << " is at index " << index << std::endl;
} else {
std::cout << "Number " << x << " is not in the array" << std::endl;
}

x = 30;
index = interpolationSearch(arr, x);

if (index != -1) {
std::cout << "Number " << x << " is at index " << index << std::endl;
} else {
std::cout << "Number " << x << " is not in the array" << std::endl;
}

return 0;
}