int[] arr1 = new int[] { 1, 3, 4, 5, 6, 9, 13, 25, 36, 45, 67 ,79};
foreach (int i in arr1)
Console.Write(i + " ");//遍历数组
Console.WriteLine("
数组长度为:" + arr1.Length + "
请输入要查找的数字:");
int num;
try
{
num = Convert.ToInt32(Console.ReadLine());
}
catch(Exception ex)
{
Console.WriteLine("输入错误!!
错误信息是:" + ex.Message);
Console.ReadLine();
return;
}
if (arr1.Contains(num))//判断数组是否包含要查找的数
{
int a = 0 , b = arr1.Length -1 ,c ;
while (a <= b)//条件判断中含有a = b ,可以有效查找两头 防止死循环
{
c = (a + b) / 2;
if (arr1[c] == num)
{
Console.WriteLine("您要找的数字是数组第" + (c + 1) +"位。");
break;
}
else if (arr1[c] > num)
b = c - 1;//已经判断中间位置不等于要查找的数 可以多移一位增加效率
else
a = c + 1;
}
}
else
Console.WriteLine("您要查找的数字不在数组内!");
Console.ReadLine();