Javatpoint Logo
Javatpoint Logo

C++ Program to Implement Interpolation Search Algorithm

Int?rpolation S?arch is an algorithm devel???d to search ?ffectively a targ?t valu? in a sort?d array. In contrast to binary search which always inspects the mid-element of search interval, interpolation search makes a more informed estimate of the target's position based on values at the endpoints of the interval. This method is highly effective when values in the array are not uniformly distributed.

The fundamental principle of interpolation search is predicting the likely location of the target in the array through a mathematical equation. This formula takes into account values of the endpoints of the search interval and assumes a linear relationship between array indices and corresponding values. The intention is to reduce the search space quicker than binary search, which always selects the middle element, especially when the distribution of values is not symmetric.

Th?n, th? algorithm ch?cks if th? ?stimat?d position is th? r?al position ?f th? k?y. If th? k?y us f?und in thi? position, t?n search is succ?ssful. Otherwise, the algorithm updates the search interval by either changing either the low or high endpoint due to comparing the key with the values at the estimated position.

The fundamental id?a of Int?rpolation S?arch is to find approximate location of the target element using its value and the range of values in the array.

H?r?,

  • The low and high are the indicators that characterize the current search interval.
  • arr[low] and arr[high] are the values at those indices.
  • k?? is the searching element.
  • pos is th? approximate position of th? key in th? array.

The idea is that if the array elements are evenly distributed, this formula gives a more accurate estimation of the key position. However, if th? array is not evenly distributed, th? int?rpolation s?arch may degenerate to binary search in th? worst case.

Th? algorithm th?n compar?s th? ?stimat?d position (arr[pos])with th? k?y:

If arr[pos]=k?y, the element is located in position pos.

If arr[pos] > key, then the key is likely in the left half, so the search interval is updated to the first half(high = pos-1).

Otherwise, if arr[pos]<k?y, then the search is shifted to the right half by updating the search interval to the right half(low=pos+1).

This search lasts until the key is situated or the search interval becomes empty. The efficacy of an interpolation search is improved where practically all elements of the array are equally divided.

The key feature of interpolation search is that it varies its behaviour depending on the arrangement of values in the array. When the values are equally spaced, the interpolation formula implies a linear relation, and the search reduces to logarithmic searching binary search. Yet if the values are not evenly distributed, the formula equalizes the process therefore bring convergence to the desired value faster.

Approach-1: Standalon? Function

Implementing a standalone function method of Int?rpolation S?arch algorithm in C++ requires creation of a standalone function located out of any class with operations in accordance with the interpolation formula. This approach is straightforward and comprehensible, which makes it appropriate for the smaller programs, where 'search' is relatively another task.

Program:

Output:

Ent?r th? k?y to s?arch: 14
K?y found at ind?x 6

Explanation:

This algorithm is applied to find a given key quickly in a sorted array. The interpolationSearch() function wraps the search process logic.

  • Standalon? Function - Int?rpolation S?arch:

The core part of the code is the interpolation search function. This function uses the interpolation search algorithm that searches for the likely location of the key in the sorted array based on the key's value and the array elements' distribution.

  • Initialization of S?arch Int?rval:

The method starts with two parameters, low and high, which represent the parameters of the current search interval. To begin with, the entire array is taken; therefore, low is set to 0, and high is set to n - 1, where n is the size of the array.

  • Int?rpolation Formula:

In a while loop, the function determines the approximate position of the key using an interpolation formula. These formulas change the position depending on the relationship of the key in the array and use values of the low and high indices.

  • Comparison and Adjustm?nt:

Th?n th? function compares th? valu? there (arr [pos]) with th? key. If both values are equivalent, the function returns the index value of pos; the key has been found. Because th? v?lue at arr[pos] is h?r? gr?at?r than th? k?y, it f?ll?ws that the key is lik?ly in th? l?ft section of th? array.

In this case, the search interval is accordingly shifted (high = pos - 1). On the contrary, if the value is less than the key, the key is most likely in the right half, and the search interval is adjusted to the right (low = pos + 1).

  • Loop T?rmination:

Th? whil? loop executes until th? s?arch interval becomes empty (low > high) or until th? k?y is found. If th? key is not present in th? array, th? function returns -1.

  • Main Function - Us?r Input and Function Call:

The main function shows the use of the interpolation search function. It initiates an example array and takes user input to search for the key. Th? interpolationSearch fun?tion is th?n c?ll?d with th? array, its size, and key as ?rguments.

  • R?sult:

The Output of the interpolation search is saved in the result variable. Thus, the main action returns if the key was found and, if yes, at which index. If th? k?y is not found, a m?ssag? that th? k?y is n?t present in th? array is d?splay?d.

Compl?xity Analysis:

Time Complexity:

Int?rpolation S?arch algorithm's time complexity varies according to the type of input data and the structures of the array elem?nt?. Ideally, if the data is uniformly distributed, the algorithm will run at an average time complexity of O(log n). But, in the worst case, when the distribution is non-uniform and draws close to linear search, time complexity can degenerate to O(n).

B?st Cas?:

Ideally, the interpolation search functions as a binary search with O(log n) complexity. This occurs when the array elements are uniformly spaced out, and the interpolation formula always narrows down the search space.

Worst Cas?:

In the worst-case scenario, the interpolation search can break down to O(n) time performance, getting close to a linear search. This happens due to the unequal allocation of array elements, which results in the interpolation formula yielding inaccurate estimates of the key's location.

Spac? Compl?xity Analysis:

The space complexity of the Interpolation Search algorithm is determined by two variables allocated to the indexing and storage of the input data. In this specific C++ implementation, the primary complexity components are the input array( arr), variables utilized within the int?rpolationSearch function (low, high, pos, key), and any other variables used in the main function ( n and result).

Input Array:

The sp??e complexity is determined by the size of th? input arr, which is proportional to th? number of el?m?nts in th? array (n). So, the space complexity is O(n).

Local Variabl?s:

The search process is controlled by low, high, pos and key variables used in the interpolation search function. These variables have constant space complexities, and their effect on space is considered O(1).

Additional Variabl?s:

The n variable in the main function represents the size of the array, which takes O(1) space. T h? result variabl? stores th? output of th? interpolation search and also requires O(1) spac?.

Approach 2: Class Impl?m?ntation

The "Class Impl?m?ntation" approach to th? Int?rpolation S?arch algorithm encapsulates th? s?arch logic into a class of the structure. Organizing code conforms to the principles of object orientation, improving the capsulation and making possible potential code reuse. Th? class, Int?rpolation S?arch, encapsulates th? inteprol?tion s?arch functionality inside a static m?thod, s?arch.

This d?sign encourages a more m?dular and structured codebase, which f?rces the search algorithm to be easy to integrate into l?rger syst?ms or simply r?use across different parts of a program. The class-based structure also provides a clearly defined namespace for the search functionality, reducing conflict in naming in more extensive codebases and improving code maintainability.

Program:

Output:

Ent?r th? k?y to s?arch: 18
K?y found at ind?x 8

Explanation:

  • The Class Impl?m?ntation approach to th? Int?rpolation S?arch algorithm is organized around encapsulating and functionality with a class called Int?rpolationS?arch. This design is consistent with object-oriented programming principles by enhancing encapsulation and the potential for code reuse.
  • The core of the implementation is the search method within the class Int?rpolationS?arch. Through d?claring thi? m?th?d as a stat?c, it b?comes accessible without th? need to create an instanc? of th? class. This static method encapsulates the int?rpolation search logic and provides a c?herent and modular user interface.
  • The search method defines two variables, low and high, representing the boundaries of the current search interval, just as in the standalone function approach. It uses th? interpolation f?rmula within th? whil? loop to estimate th? probable location of th? key. The logic for internal search within the loop retains relative consistency with the standalone function approach, including comparisons and adjustments to shrink the search space.
  • This class-based structure has several strengths. To begin with, it encourages encapsulation because it groups the logic of search in a class and prevents direct access to internal variables and methods. This improves code structure and reduces the risk of interference with other program parts.
  • Subsequently, th? class impl?m?ntation provides ?n?th?r nam?space for a th? search function. This separation minimizes naming conflicts in larger codebases where many functions or classes may share similar names. Thus, it helps to improve code maintainability and readability.
  • Moreover, the class-based approach promotes possible code reuse. Due to its encapsulated search method, The Int?rpolationS?arch class can easily be integrated into different program parts or even reused in entirely different programs. These modularity properties and r?usability are integral to developing scalable and maintainable software systems.

Compl?xity Analysis:

Tim? compl?xity Analysis:

The time complexity of the Int?rpolation S?arch algorithm when implemented with the Class Impl?m?ntation approach does not differ from this method. In the best-case scenario, the average time complexity is O(log n) when the data is distributed uniformly.

However, in the worst case where non-uniform distribution approaches linear search, the time complexity becomes O(n). Since the interpolation search algorithm does reasonably well when the data is evenly distributed, it could degrade when skewed.

Spac? compl?xity Analysis:

In spac? compl?xity, th? primary contributors ar? th? input array (arr[]), th? variabl?s us?d within th? Int?rpolationS?arch: search method (low, high, pos, key), and other variables in the main function (n and result). The spac? compl?xity is O(n) due to the input array, and th? additional spac? r?quir?d by local variabl?s and param?t?rs is O(1), m?king th? total spac? compl?xity O(n). The class-bas?d approach add?s a rel?tively small additi?nal space compl?xity, preserving th? efficiency of th? int?rpolation s?arch algorithm.

Approach-3: R?cursiv? Impl?m?ntation

Recursive impl?m?ntation of th? Int?rpolation S?arch algorithm uses a function that repeatedly splits th? s?arch interval in half until th? key is f?und or th? interval becomes invalid.

Th? r?cursiv? function ch?cks th? search int?rval's validity, ?stimat?s th? p?siti?n ?f th? k?y b?s?d ?n th? int?rpolation f?rmula, and mak?s r?cursiv? calls bas?d on comparisons b? This strat?gy is very useful due to this concise expression of th? search logic, which resembles th? inherent divide-and-conquer nature of the problem

Program:

Output:

Ent?r th? k?y to s?arch: 13
K?y not found in th? array.

Explanation:

The provided C++ code illustrates a recursive version of the Int?rpolation S?arch algorithm.

  • R?cursiv? Function - int?rpolationS?archR?cursiv?:

The core of th? cod? lies in th? int?rpolationS?archR?cursiv? functi?n. This r?cursiv? function performs the Int?rpolation S?arch algorithm. It tak?s four param?t?rs: th? sorted array arr[], th? lower index low of th? current search interval, th? higher index high of th? current search interval and th? key being searched.

  • Bas? Cas?:

Th? recursiv? function begins with a b?s? case that c?ecks w?ther th? s?arch int?rval is v?lid (low < = high) and wh?ther th? k?y l?es in th? curr?nt s?arch int?rval (k?y >= arr[low] && k?y<=arr[high]). If this condition fails, the recursion ends, but the function returns - 1, meaning the key is not in the array.

  • Int?rpolation Formula:

Int?rpolation formula is used i? th? function to calculate th? probabl? position (pos) of th? ??? within th? array. This formula also adapts the position based on the relative position of the key within the array in the same way as the iterative approach.

  • Comparison and R?cursiv? Calls:

Th? function th?n compares th? value at th? estimated location (arr[pos]) with th? k?y. If they're the same, then th? function r?turns th? position, meaning th?t th? k?y h?? b??n f?und. The value at arr[pos] is greater than th? k?y as ? sign that th? k?y is likely in th? l?ft half of th? array.

In this case, the function is recursively called on the left side with an updated search interval. Likewise, if the value is less than the key, the function recursively calls itself with the updated search interval on the right side.

  • Main Function:

In the main function, a sample array is created (that will have to be sorted for Int?rpolation S?arch). User input is used to search for the key. The recursive function int?rpolationS?archR?cursiv? is then call?d with th? initial search interval and th? k?y. The result is printed depending on the presence of the key.

  • R?cursiv? Natur?:

Th? r?cursiv? impl?m?ntation hides th? r?cursiv? natur? of th? function calls to manag? subint?rvals and ?fficiency the s?arch spac?. This function creates smaller parts of the array until the key is found or the search interval invalidates.

Compl?xity Analysis:

Tim? Compl?xity:

The time complexity of the recursive Int?rpolation S??r?h algorithm depends on th? d?str?bution of th? in??t data. In the best-case scenario, the average-case complexity is O(log n) when the data is uniformly distributed. However, in the worst case scenario, where the d?sp?r?u?l? that this distribution is not even and is appr???hing a 1inear s?arch, the time compl?xity is O(n).

B?st Cas?:

In the best-case situation, the recursive Interpolation Search performs comparably with its iterative counterpart, attaining an average time complexity of O(log n). This happens as an effect of the even distribution of the array element if the interpolation formula consistently contracts the search space efficiently.

Worst Cas?:

In the worst case, the time complexity can degrade to O(n). This occurs when th? array ?l?m?nts are not equally distributed, and the interpolation formula provides inaccurate estimates of th? key's position, and consequently, suboptimal search behaviour is obtained.

Spac? Compl?xity:

The space complexity of the recursive Interpolation Search algorithm is determined by the function call stack and the additional variables used in each function call. The primary sources are the input array (arr[]), the parameters of the recursive function (low, high, key), and the local variables in each function call.

Input Array:

The array size, arr, drives the space complexity arr[]. The required space for the array is proportional to the number of elements(n). Therefore, the space complexity associated with the input array is O(n).

Function Call Stack:

The recursive nature of the algorithm contributes to space complexity from the function call stack. In the best-case scenario, when the recursion effectively reduces the search space, the maximum depth of the call stack is O(log n). However, in the worst case, if the recursion behaves like a linear search, the maximum depth can be O(n).

Local Variabl?s:

The local variabl?s within each function call, such as low, high, pos, and k?y, require constant space for each call. Therefore, the space complexity related to local variables is O(1) per function call.

Conclusion:

Th? recursiv? implementation of th? Int?rpolation S?arch algorithm provides an alt?rnativ? implementation of th? it?rativ? m?thod. It describes search logic more compactly and recursively, calling functions to handle the subintervals. The code is designed for readability, and every step of the recursive Interpolation Search algorithm is explained in comments. This implementation is a valuable approach in situations where recursive techniques are well-liked.

Approach 4: T?mplat? Impl?m?ntation

In T?mplat? Impl?m?ntation, g?n?ric t?mplat?v?rsion of t?mplate Int?rpolation S?arch algorithm is writ?n in C++. With t?mplat?s, you can build a f?xible and typ?-ind?p?nd?nt imp?l?m?ntation open to different data typ?s. In this configuration, cod? r?usability and fl?xibility are intensified.

Program:

Output:

Int?g?r K?y found at ind?x 6
Float K?y found at ind?x 6

Explanation:

The provided C++ code illustrates the T?mplat? Impl?m?ntation approach for the Int?rpolation S?arch algorithm, which is generic and type-independent.

  • Function T?mplat? - int?rpolationS?arch:

The implementation of t?mplat? implementation is found in int?rpolationS?arch fi?tion, which is fixed t?mplat?. Th? paramet?r typ?nam? T th?t t?mplat? f?r a function allow? it t? w?rk w?th different data typ?s. This t?mplat? d?sign is designed in such a way as to promote flexibility and code reusability.

  • Initialization of S?arch Int?rval:

T? function t?mplat? initializes two v?riables, low and high, representing th? boundaries of th? current search range. This initialization is fundamental to th? Int?rpolation S ?arch algorithm, which allows n?ring down th? search space.

  • Int?rpolation Formula and S?arch Logic:

Inside a while loop, the interpolation formula estimates the probable key's position (pos ). The s?arch logic within th? loop is consistent with other implementations, with comp?risons and modifications to shrink th? search spac?.

  • T?mplat? Instantiation in Main Function:

In th? main function, th? t?mplat? is instanti?t?d using specific d?t? types. Th? first e??m?l? shows searching in an array of integers (intArr), ?nd th? ??e?t e??m?l? elaborates on searching in ?n array of floating-point numbers (floatArr). The Swiftness of this approach ensures that the same t?mplat? function works smoothly with different arr?ys and k??s.

Compl?xity Analysis:

Tim? Compl?xity:

Th? ?im? compl?xity of th? ?emplat? Impl?m?ntation of th? Int?rpolation S?arch algorithm sh?wn remains constant with other impl?m?ntations. The input distribution influences it, and the analysis applies only to templated and non-templated versions.

B?st Cas?:

At best, when the data is uniformly distributed, the average complexity time is O(log n). The interpolation search speeds up the search space, obtaining logarithmic time complexity.

Worst Cas?:

However, in the worst-case situation where the distribution is not uniform and nearly reaches the linear search, the time complexity becomes O(n). This process, however, does happen in cases where the interpolation formula gives incorrect estimates of the position of the key, thus leading to sub-optimal search behaviour.

Spac? compl?xity Analysis:

Due t? th? spac? compl?xity of th? T?mplat? Impl?m?ntation in th? Int?rpolation S?arch algorithm using th? input array (arr[]), it is O(n). Other spac? d?ma?d? are cr??ted by th? fu?tion c?ll stack, with max inherity of O(log n) in th? best case and O(n) in the worst case. Local variables within each function call contribute O(1) space, which sums up O(n) space complexity when considering the recursion depth.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA