forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InterpolationSearch.cs
51 lines (44 loc) · 1.42 KB
/
InterpolationSearch.cs
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
44
45
46
47
48
49
50
51
namespace Algorithms.Search;
/// <summary>
/// Class that implements interpolation search algorithm.
/// </summary>
public static class InterpolationSearch
{
/// <summary>
/// Finds the index of the item searched for in the array.
/// Algorithm performance:
/// worst-case: O(n),
/// average-case: O(log(log(n))),
/// best-case: O(1).
/// </summary>
/// <param name="sortedArray">Array with sorted elements to be searched in. Cannot be null.</param>
/// <param name="val">Value to be searched for. Cannot be null.</param>
/// <returns>If an item is found, return index, else return -1.</returns>
public static int FindIndex(int[] sortedArray, int val)
{
var start = 0;
var end = sortedArray.Length - 1;
while (start <= end && val >= sortedArray[start] && val <= sortedArray[end])
{
var denominator = (sortedArray[end] - sortedArray[start]) * (val - sortedArray[start]);
if (denominator == 0)
{
denominator = 1;
}
var pos = start + (end - start) / denominator;
if (sortedArray[pos] == val)
{
return pos;
}
if (sortedArray[pos] < val)
{
start = pos + 1;
}
else
{
end = pos - 1;
}
}
return -1;
}
}