Professional Documents
Culture Documents
S COLLEGE OF ENGINEERING
(Autonomous College under VTU)
Bull Temple Road, Bangalore-560019
6. Source Code
Python, C and Java
7. Output Screenshots
8. Reference
18MCA4PCAD INTERPOLATION SEARCH ALGORITHM
1. Introduction
Formula:-
pos = lo + [ (x-arr[lo])*(hi-lo) / (arr[hi]-arr[Lo]) ]
3. Algorithm
Step 1 − Start searching data from middle of the list.
Step 4 − Divide the list using probing formula and find the new middle.
4. Example
5. Comparison
Below table is the direct comparison of interpolation with two other
algorithms taken from the syllabus
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")
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;
}
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); }}
7. Output-Screenshot
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