- Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathInterpolationSearch.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
namespaceAlgorithms.Search;
/// <summary>
/// Class that implements interpolation search algorithm.
/// </summary>
publicstaticclassInterpolationSearch
{
/// <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>
publicstaticintFindIndex(int[]sortedArray,intval)
{
varstart=0;
varend=sortedArray.Length-1;
while(start<=end&&val>=sortedArray[start]&&val<=sortedArray[end])
{
vardenominator=(sortedArray[end]-sortedArray[start])*(val-sortedArray[start]);
if(denominator==0)
{
denominator=1;
}
varpos=start+(end-start)/denominator;
if(sortedArray[pos]==val)
{
returnpos;
}
if(sortedArray[pos]<val)
{
start=pos+1;
}
else
{
end=pos-1;
}
}
return-1;
}
}