-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path102-interpolation.c
43 lines (38 loc) · 1.08 KB
/
102-interpolation.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include "search_algos.h"
/**
* interpolation_search - Searches for a value in a sorted array
* of integers using interpolation search.
* @array: A pointer to the first element of the array to search.
* @size: The number of elements in the array.
* @value: The value to search for.
*
* Return: If the value is not present or the array is NULL, -1.
* Otherwise, the first index where the value is located.
*
* Description: Prints the value every time it is compared in the array.
*/
int interpolation_search(int *array, size_t size, int value)
{
size_t low, high;
if (array == NULL)
return (-1);
for (low = 0, high = size - 1; high >= low;)
{
size_t pos = low + (((double)(high - low) / (array[high] - array[low])) *
(value - array[low]));
if (pos < size)
printf("Value checked array[%ld] = [%d]\n", pos, array[pos]);
else
{
printf("Value checked array[%ld] is out of range\n", pos);
break;
}
if (array[pos] == value)
return (pos);
if (array[pos] > value)
high = pos - 1;
else
low = pos + 1;
}
return (-1);
}