2020-05-29 23:23:24 +03:00
|
|
|
#include <stdio.h>
|
2019-08-03 02:52:21 +03:00
|
|
|
|
|
|
|
/* By comparison, binary search always chooses the middle of the remaining
|
|
|
|
* search space, discarding one half or the other, depending on the comparison
|
2020-05-29 23:23:24 +03:00
|
|
|
* between the key found at the estimated position and the key sought. The
|
|
|
|
* remaining search space is reduced to the part before or after the estimated
|
|
|
|
* position. The linear search uses equality only as it compares elements
|
|
|
|
* one-by-one from the start, ignoring any sorting. On average the interpolation
|
|
|
|
* search makes about log(log(n)) comparisons (if the elements are uniformly
|
|
|
|
* distributed), where n is the number of elements to be searched. In the worst
|
|
|
|
* case (for instance where the numerical values of the keys increase
|
|
|
|
* exponentially) it can make up to O(n) comparisons. In
|
|
|
|
* interpolation-sequential search, interpolation is used to find an item near
|
|
|
|
* the one being searched for, then linear search is used to find the exact
|
|
|
|
* item. */
|
2019-08-03 02:52:21 +03:00
|
|
|
|
|
|
|
int interpolationSearch(int arr[], int n, int key)
|
|
|
|
{
|
|
|
|
int low = 0, high = n - 1;
|
2020-05-29 23:23:24 +03:00
|
|
|
while (low <= high && key >= arr[low] && key <= arr[high])
|
|
|
|
{
|
2019-08-03 02:52:21 +03:00
|
|
|
/* Calculate the nearest posible position of key */
|
2020-05-29 23:23:24 +03:00
|
|
|
int pos =
|
|
|
|
low + ((key - arr[low]) * (high - low)) / (arr[high] - arr[low]);
|
2019-08-03 02:52:21 +03:00
|
|
|
if (key > arr[pos])
|
|
|
|
low = pos + 1;
|
|
|
|
else if (key < arr[pos])
|
|
|
|
high = pos - 1;
|
|
|
|
else /* Found */
|
|
|
|
return pos;
|
2018-03-07 21:11:38 +03:00
|
|
|
}
|
2019-08-03 02:52:21 +03:00
|
|
|
/* Not found */
|
2018-03-07 21:11:38 +03:00
|
|
|
return -1;
|
|
|
|
}
|
2019-08-03 02:52:21 +03:00
|
|
|
|
2018-03-07 21:11:38 +03:00
|
|
|
int main()
|
|
|
|
{
|
2018-03-14 00:38:07 +03:00
|
|
|
int x;
|
2020-05-29 23:23:24 +03:00
|
|
|
int arr[] = {10, 12, 13, 16, 18, 19, 20, 21, 22, 23, 24, 33, 35, 42, 47};
|
|
|
|
int n = sizeof(arr) / sizeof(arr[0]);
|
2019-08-03 02:52:21 +03:00
|
|
|
|
|
|
|
printf("Array: ");
|
2020-05-29 23:23:24 +03:00
|
|
|
for (int i = 0; i < n; i++)
|
2019-08-03 02:52:21 +03:00
|
|
|
printf("%d ", arr[i]);
|
|
|
|
printf("\nEnter the number to be searched: ");
|
2020-05-29 23:23:24 +03:00
|
|
|
scanf("%d", &x); /* Element to be searched */
|
2019-08-03 02:52:21 +03:00
|
|
|
|
2018-03-07 21:11:38 +03:00
|
|
|
int index = interpolationSearch(arr, n, x);
|
2019-08-03 02:52:21 +03:00
|
|
|
|
|
|
|
/* If element was found */
|
2018-03-07 21:11:38 +03:00
|
|
|
if (index != -1)
|
2019-08-03 02:52:21 +03:00
|
|
|
printf("Element found at position: %d\n", index);
|
2018-03-07 21:11:38 +03:00
|
|
|
else
|
2019-08-03 02:52:21 +03:00
|
|
|
printf("Element not found.\n");
|
2018-03-07 21:11:38 +03:00
|
|
|
return 0;
|
|
|
|
}
|