Interpolation Search in an Sorted Array - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Interpolation Search in an Sorted Array

Share This
Interpolation search is a searching algorithm designed for sorted datasets. Unlike linear search, which checks each element sequentially, or binary search, which repeatedly divides the search space in half, interpolation search takes a more informed approach. It leverages the sorted nature of the data to estimate the potential position of the target element.

This estimation relies on a mathematical concept called interpolation. Imagine searching a phone directory for a specific name. You wouldn't start at the beginning and flip through every page. Instead, you'd likely consider the thickness of the book and the alphabetical order to target a section closer to your desired name. Interpolation search works similarly, using the value of the target element and the range of values in the sorted array to predict a more efficient search location.

The importance of interpolation search lies in its potential for faster search times compared to other algorithms, particularly for uniformly distributed data. By making intelligent guesses about the target's location, it can significantly reduce the number of comparisons needed to find the element or determine its absence. This efficiency becomes especially crucial when dealing with large datasets, where minimizing search time is critical for application performance.

Source Code
#include<stdio.h> #include<stdlib.h> int main() { int n, key, count = 0; int i, index = -1, left, right, temp; int *p; printf("Enter the number of inputs:"); scanf("%d", &n); p = (int *)malloc(n * sizeof(int)); printf("Enter the values :"); for (i = 0; i < n; i++) { scanf("%d", &p[i]); } printf("Enter the key (which will be searched):"); scanf("%d", &key); left = 0; right = n; while (left < right) { count++; printf("%d %d %d\n", count, left, right); temp = left + (((double)(right - left) * (key - p[left])) / (p[right] - p[left])); printf("%d %d %d %d\n", count, left, right, temp); if(p[temp] == key) { index = temp; break; } else if(p[temp] < key) left = temp + 1; else right = temp - 1; } if(index == -1) printf("The key not found!\n"); else printf("The key is present at index %d at iteration %d!\n", index, count); return 0; }



Happy Exploring!

No comments:

Post a Comment