数据检索算法是指从数据集合(数组、表、哈希表等)中检索指定的数据项。
数据检索算法是所有算法的基础算法之一。
本文发布 三元搜索(Ternary Search)的源代码。
1 文本格式
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>
static int Ternary_Search(int[] arr, int left, int right, int x)
{
if (right >= left)
{
int mid1 = left + (right - left) / 3;
int mid2 = mid1 + (right - left) / 3;
if (arr[mid1] == x)
{
return mid1;
}
if (arr[mid2] == x)
{
return mid2;
}
if (arr[mid1] > x)
{
return Ternary_Search(arr, left, mid1 - 1, x);
}
if (arr[mid2] < x)
{
return Ternary_Search(arr, mid2 + 1, right, x);
}
return Ternary_Search(arr, mid1 + 1, mid2 - 1, x);
}
return -1;
}
}
}
——————————————————————
POWER BY 315SOFT.COM &
TRUFFER.CN
2 代码格式
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>static int Ternary_Search(int[] arr, int left, int right, int x){if (right >= left){int mid1 = left + (right - left) / 3;int mid2 = mid1 + (right - left) / 3;if (arr[mid1] == x){return mid1;}if (arr[mid2] == x){return mid2;}if (arr[mid1] > x){return Ternary_Search(arr, left, mid1 - 1, x);}if (arr[mid2] < x){return Ternary_Search(arr, mid2 + 1, right, x);}return Ternary_Search(arr, mid1 + 1, mid2 - 1, x);}return -1;}}
}