0
点赞
收藏
分享

微信扫一扫

C#,数据检索算法之插值搜索(Interpolation Search)的源代码

钵仔糕的波波仔 2022-04-22 阅读 89
c#算法

数据检索算法是指从数据集合(数组、表、哈希表等)中检索指定的数据项。

数据检索算法是所有算法的基础算法之一。

本文提供插值搜索(Interpolation Search)的源代码。

using System;

namespace Legalsoft.Truffer.Algorithm
{
	public static class ArraySearch_Algorithm
	{
		/// <summary>
		/// 插值搜索
		/// </summary>
		/// <param name="arr"></param>
		/// <param name="left"></param>
		/// <param name="right"></param>
		/// <param name="x"></param>
		/// <returns></returns>
		public static int Interpolation_Search(int[] arr, int left, int right, int x)
		{
			int pos;
			if (left <= right && x >= arr[left] && x <= arr[right])
			{
				pos = left + (((right - left) / (arr[right] - arr[left])) * (x - arr[left]));
				if (arr[pos] == x)
				{
					return pos;
				}
				if (arr[pos] < x)
				{
					return Interpolation_Search(arr, pos + 1, right, x);
				}
				if (arr[pos] > x)
				{
					return Interpolation_Search(arr, left, pos - 1, x);
				}
			}
			return -1;
		}

	}
}

————————————————————

POWER BY TRUFFER.CN

举报

相关推荐

0 条评论