-
Notifications
You must be signed in to change notification settings - Fork 0
/
102-interpolation.c
42 lines (37 loc) · 1.02 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
#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 a value every time it is compared in the array..
*/
int interpolation_search(int *array, size_t size, int value)
{
size_t i, l, r;
if (array == NULL)
return (-1);
for (l = 0, r = size - 1; r >= l;)
{
i = l + (((double)(r - l) / (array[r] - array[l])) * (value - array[l]));
if (i < size)
printf("Value checked array[%ld] = [%d]\n", i, array[i]);
else
{
printf("Value checked array[%ld] is out of range\n", i);
break;
}
if (array[i] == value)
return (i);
if (array[i] > value)
r = i - 1;
else
l = i + 1;
}
return (-1);
}