[C#] 纯文本查看 复制代码
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
int[] array = { 10, 25, 31, 36, 42, 49, 56, 71, 77, 88, 96, 100,111 };
ShowSord(array);
Console.Write("...........................");
int returnIndex = TwoPointsSearch(array, 25, 0, array.Length - 1);
Console.Write("数组元素{0}的索引为{1}", 25, returnIndex.ToString());
Console.ReadKey();
}
///
/// 输出数组所有元素
///
///
private static void ShowSord(int[] array)
{
foreach (var num in array)
{
Console.Write($"{num} ");
}
Console.WriteLine();
Console.Write("数组长度为{0}", array.Length.ToString());
Console.WriteLine();
}
///
/// 返回索引,不存在则返回-1
///
///
///
///
///
///
public static int TwoPointsSearch(int[] array,int data, int leftIndex,int rightIndex)
{
int MiddleIndex = (leftIndex + rightIndex) / 2;
if (leftIndex > rightIndex)
{
return -1;
}
//不存在返回-1;
else
{
if (array[MiddleIndex] == data)
{
return MiddleIndex;
}
else
{
if (array[MiddleIndex] > data)
{
return TwoPointsSearch(array, data, leftIndex, MiddleIndex-1);
}
else
{
return TwoPointsSearch(array, data, MiddleIndex+1, rightIndex);
}
}
}
}
}
}