二分查找(Binary Search)是一種高效的查找算法,它適用于已排序的數(shù)據(jù)集合。在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#中的應用場景非常廣泛,只要是在已排序的數(shù)據(jù)結(jié)構(gòu)中查找元素,都可以考慮使用二分查找來提高查找效率。