15个数按从小到大的顺序放在一个数组中,输入一个数,用折半查找法找出该数是数组中第几个元素的值?

该数不再数组中,则输出“无此数”
2024-12-03 18:51:10
推荐回答(1个)
回答1:

C#:
public string GetIndex(int[] IntArray, int num)//缓旅腊数组和要找的数字
{
string ShowIndex = "";
int n = IntArray.Length;
int leftindex = 0;
int rightindex = n - 1;
int middleindex = (n - 1) / 2;
int find = 0;
while (leftindex <= rightindex)
{
middleindex = (leftindex + rightindex) /镇扰 2;
if (num == IntArray[middleindex])
{ ShowIndex = "数组第" + (middleindex + 1) + "个元素为扰滑" + num; find = 1; break; }
else if (num < IntArray[middleindex]) { rightindex = middleindex - 1; }
else { leftindex = middleindex + 1; }
}
if (find == 0)
ShowIndex = "无此数";
return ShowIndex;
}