二分查找(Binary Search)是一种高效的查找算法,它适用于已排序的数据集合。在C#中,二分查找可以应用于多种场景,以下是一些常见的应用场景:
int[] sortedArray = new int[] { 1, 3, 5, 7, 9, 11, 13, 15 };
int target = 11;
int index = Array.BinarySearch(sortedArray, target);
if (index >= 0)
{
Console.WriteLine($"Target found at index: {index}");
}
else
{
Console.WriteLine("Target not found");
}
List<int> sortedList = new List<int> { 1, 3, 5, 7, 9, 11, 13, 15 };
int target = 11;
int index = sortedList.BinarySearch(target);
if (index >= 0)
{
Console.WriteLine($"Target found at index: {index}");
}
else
{
Console.WriteLine("Target not found");
}
SortedDictionary<int, string> sortedDictionary = new SortedDictionary<int, string>
{
{ 1, "one" },
{ 3, "three" },
{ 5, "five" },
{ 7, "seven" },
{ 9, "nine" },
};
int targetKey = 5;
if (sortedDictionary.ContainsKey(targetKey))
{
Console.WriteLine($"Target key found with value: {sortedDictionary[targetKey]}");
}
else
{
Console.WriteLine("Target key not found");
}
SortedSet<int> sortedSet = new SortedSet<int> { 1, 3, 5, 7, 9, 11, 13, 15 };
int target = 11;
if (sortedSet.Contains(target))
{
Console.WriteLine("Target found in the sorted set");
}
else
{
Console.WriteLine("Target not found");
}
总之,二分查找在C#中的应用场景非常广泛,只要是在已排序的数据结构中查找元素,都可以考虑使用二分查找来提高查找效率。