Skip to content

Commit

Permalink
Create in_CPP.cpp (#167)
Browse files Browse the repository at this point in the history
* Create in_CPP.cpp

Added interpolation search in cpp

* Rename Searching/in_CPP.cpp to Interpolation Search/in_CPP.cpp

Renamed the folder to interpolation search.

* Rename Interpolation Search/in_CPP.cpp to Searching/Interpolation-Searching/in_CPP.cpp

Added interpolation search in cpp in existing inerpolation search folder

* Rename Searching/Interpolation-Searching/in_CPP.cpp to Searching/Interpolation-Search/in_CPP.cpp
  • Loading branch information
shardendu930 authored Oct 30, 2022
1 parent 2bebc43 commit 482fee6
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions Searching/Interpolation-Search/in_CPP.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/* C++ program to implement interpolation
search.
The Interpolation Search is an improvement over Binary Search for instances, where the values in a sorted array are uniformly distributed.
Interpolation constructs new data points within the range of a discrete set of known data points. Binary Search always goes to the middle element to check.
On the other hand, interpolation search may go to different locations according to the value of the key being searched.
For example, if the value of the key is closer to the last element, interpolation search is likely to start search toward the end side.
Time Complexity: O(log2(log2 n)) for the average case, and O(n) for the worst case
Auxiliary Space Complexity: O(1)
*/

#include <bits/stdc++.h>
using namespace std;

int interpolationSearch(int arr[], int lo, int hi, int x)
{
int pos;

if (lo <= hi && x >= arr[lo] && x <= arr[hi]) {

pos = lo
+ (((double)(hi - lo) / (arr[hi] - arr[lo]))
* (x - arr[lo]));
if (arr[pos] == x)
return pos;

if (arr[pos] < x)
return interpolationSearch(arr, pos + 1, hi, x);

if (arr[pos] > x)
return interpolationSearch(arr, lo, pos - 1, x);
}
return -1;
}

int main()
{

int arr[] = { 10, 12, 13, 16, 18, 19, 20, 21,
22, 23, 24, 33, 35, 42, 47 };

int n = sizeof(arr) / sizeof(arr[0]);

int x = 18;
int index = interpolationSearch(arr, 0, n - 1, x);

if (index != -1)
cout << "Element found at index " << index;
else
cout << "Element not found.";

return 0;
}

0 comments on commit 482fee6

Please sign in to comment.