You are on page 1of 14

B.M.

S COLLEGE OF ENGINEERING
(Autonomous College under VTU)
Bull Temple Road, Bangalore-560019

DEPARTMENT OF COMPUTER APPLICATIONS

ADA AAT REPORT


Title: Interpolation Search

Team Members: Roles:


Bharath V (1BM19MCA11) Coding
Shruti Shree (1BF19MCA14) Coding
Shiwangi Pradhan (1BF19MCA11) Documentation and Compilation
Jonathan Zoremsanga Fanai (1BM19MCA19) Coding

Under the Guidance:


Pushpa T S

4th Semester 2021


Abstract
The topic chosen for the AAT of this semester is on Interpolation Search. We have
chosen this topic keeping in mind the importance of efficient searching algorithms. From
our syllabus we have learned that Binary search has a huge advantage of time
complexity over linear search to further enhance this we are introducing the
Interpolation Searching method
CONTENTS
1. Introduction
Explanation and Formula

2. Time and Space Complexity


3. Algorithm
4. Example
5. Comparison
Binary vs. Linear vs. Interpolation

6. Source Code
Python, C and Java

7. Output Screenshots
8. Reference
18MCA4PCAD INTERPOLATION SEARCH ALGORITHM

1. Introduction

Interpolation is a statistical method or a mathematical concept by which related


known values are used to estimate a value; it is achieved by using other
established values that are located in sequence with the unknown value. It has a
various number of applications in engineering and science that are used to
construct new data points within the range of a discrete data set of known data
points.

The Interpolation Search is an improvement over Binary Search for instances,


where the values in a sorted array are uniformly distributed. 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.

Formula:-
pos = lo + [ (x-arr[lo])*(hi-lo) / (arr[hi]-arr[Lo]) ]

arr[] ==> Array where elements need to be searched


x ==> Element to be searched
lo ==> Starting index in arr[]
hi ==> Ending index in arr[]

Master of Computer Application 4


18MCA4PCAD INTERPOLATION SEARCH ALGORITHM

2. Time and Space Complexity


 Time Complexity: O(log2(log2 n)) for the average case, and O(n) for the worst
case (when items are distributed exponentially)

 Space Complexity: O(1)

3. Algorithm
Step 1 − Start searching data from middle of the list.

Step 2 − If it is a match, return the index of the item, and exit.

Step 3 − If it is not a match, probe position.

Step 4 − Divide the list using probing formula and find the new middle.

Step 5 − If data is greater than middle, search in higher sub-list.

Step 6 − If data is smaller than middle, search in lower sub-list.

Step 7 − Repeat until match.

Master of Computer Application 5


18MCA4PCAD INTERPOLATION SEARCH ALGORITHM

4. Example

Here, Let’s find the array position of the element 9


l=0 a[l]=1
h=7 a[h]=15
x=9
Pos = l + [ (x-arr[lo])*(h-l) / (arr[h]-arr[l]) ]
= 0 + [(9 - 1) * (7 - 0) / (15-1)]
= 0 + [(8 * 7) / 14]
= 0 + (56 / 14)
=0+4
=4

Therefore, the element 9 is located in the array position 4

Master of Computer Application 6


18MCA4PCAD INTERPOLATION SEARCH ALGORITHM

5. Comparison
Below table is the direct comparison of interpolation with two other
algorithms taken from the syllabus

Time Complexity Space Complexity


Best Worst Average Best Worst Average
Case Case Case Case Case Case
Linear
O(1) O(n) O(n) O(1) O(1) O(1)
search
Binary
Search O(1) O (log n) O (log n) O(1) O(1) O(1)
(Iterative)
Binary
Search O(1) O (log n) O (log n) O(1) O (log n) O (log n)
(Recursive)

Interpolati O (log log


O(1) O(n) O(1) O(1) O(1)
on Search n)

Master of Computer Application 7


18MCA4PCAD INTERPOLATION SEARCH ALGORITHM

6. Source Codes
Below are the codes for implementing the interpolation search algorithm
written in python, C and java

6.1. Python:-
def interpolation_search(sorted_collection, item):
left = 0
right = len(sorted_collection) - 1
while left <= right:
# avoid divided by 0 during interpolation
if sorted_collection[left] == sorted_collection[right]:
if sorted_collection[left] == item:
return left
else:
return None
point = left + ((item - sorted_collection[left]) * (right - left)) // (
sorted_collection[right] - sorted_collection[left]
)
# out of range check
if point < 0 or point >= len(sorted_collection):
return None
current_item = sorted_collection[point]
if current_item == item:
return point
else:
if point < left:
right = left
left = point
elif point > right:
left = right
right = point
else:
if item < current_item:
right = point - 1
else:
left = point + 1
return None
def __assert_sorted(collection):
if collection != sorted(collection):
raise ValueError("Collection must be ascending sorted")
return True
if __name__ == "__main__":
Master of Computer Application 8
18MCA4PCAD INTERPOLATION SEARCH ALGORITHM

import sys
debug = 0
n=int(input("Enter the number of elements: "))
collection=[]
for i in range(n):
ele=int(input())
collection.append(ele)
target=int(input("Enter the element to be searched: "))
if debug == 1:
try:
__assert_sorted(collection)
except ValueError:
sys.exit("Sequence must be ascending sorted to apply interpolation search")
result = interpolation_search(collection, target)
if result is not None:
print(f"{target} found at positions: {result}")
else:
print("Not found")

Master of Computer Application 9


18MCA4PCAD INTERPOLATION SEARCH ALGORITHM

6.2. C:-
#include <stdio.h>
int interpolationSearch(int arr[], int n, int key)
{
int low = 0, high = n - 1;
while (low <= high && key >= arr[low] && key <= arr[high])
{
/* Calculate the nearest posible position of key */
int pos = low + ((key - arr[low]) * (high - low)) / (arr[high] - arr[low]);
if (key > arr[pos])
low = pos + 1;
else if (key < arr[pos])
high = pos - 1;
else /* Found */
return pos;
}
/* Not found */
return -1;
}
int main()
{
int x;
int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47};
int n = sizeof(arr) / sizeof(arr[0]);

printf("Array: ");
for (int i = 0; i < n; i++)
printf("%d ", arr[i]);
printf("\nEnter the number to be searched: ");
scanf("%d", &x); /* Element to be searched */
int index = interpolationSearch(arr, n, x);
/* If element was found */
if (index != -1)
printf("Element found at position: %d\n", index);
else
printf("Element not found.\n");
return 0;
}

Master of Computer Application 10


18MCA4PCAD INTERPOLATION SEARCH ALGORITHM

6.3. Java;-
import java.util.Scanner;
public class InterpolationSearch
{
public static int interpolationSearch(int[] sortedArray, int toFind)
{
int low = 0;
int high = sortedArray.length - 1;
int mid;
while (sortedArray[low] <= toFind && sortedArray[high] >= toFind)
{
if (sortedArray[high] - sortedArray[low] == 0)
return (low + high)/2;
mid = low + ((toFind - sortedArray[low]) * (high - low)) / (sortedArray[high] -
sortedArray[low]);
if (sortedArray[mid] < toFind)
low = mid + 1;
else if (sortedArray[mid] > toFind)
high = mid - 1;
else
return mid;
}
if (sortedArray[low] == toFind)
return low;
else
return -1;
}
public static void main(String[] args)
{
Scanner scan = new Scanner( System.in );
System.out.println("Interpolation Search Test\n");
int n, i;
System.out.println("Enter number of integer elements");
n = scan.nextInt();
int arr[] = new int[ n ];
System.out.println("\nEnter "+ n +" sorted integer elements");
for (i = 0; i < n; i++)
arr[i] = scan.nextInt();
System.out.println("\nEnter element to search for : ");
int key = scan.nextInt();
int result = interpolationSearch(arr, key);
if (result == -1)
System.out.println("\n"+ key +" element not found");
else
System.out.println("\n"+ key +" elemnt found at position "+ result); }}

Master of Computer Application 11


18MCA4PCAD INTERPOLATION SEARCH ALGORITHM

7. Output-Screenshot

Output of the above programs for Python,C and java respectively

7.1. Python output for Interpolation.py

7.2) C output for interpolation.exe

Master of Computer Application 12


18MCA4PCAD INTERPOLATION SEARCH ALGORITHM

7.3) Java output for Interpolation

Master of Computer Application 13


18MCA4PCAD INTERPOLATION SEARCH ALGORITHM

8. References

 https://www.techiedelight.com/interpolation-search/

 https://www.youtube.com/watch?v=hF9iJEPegNc&ab_channel=TEC
HDOSE

 https://www.youtube.com/watch?v=4aNiNNNjlXc&ab_channel=Digi
iMento%3AGATE%2CNTANET%26OtherCSEExamPrep

 https://www.youtube.com/watch?v=-
MPTAD4z0gY&ab_channel=CodeWhoop

Master of Computer Application 14

You might also like