18 Star 133 Fork 63

编程语言算法集 / C-Sharp

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
InterpolationSearch.cs 1.42 KB
一键复制 编辑 原始数据 按行查看 历史
Gerson Jr 提交于 2023-12-31 09:48 . Switch to file-scoped namespaces (#431)
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;
}
}
C#
1
https://gitee.com/TheAlgorithms/C-Sharp.git
git@gitee.com:TheAlgorithms/C-Sharp.git
TheAlgorithms
C-Sharp
C-Sharp
master

搜索帮助