算法3 ----二分法查找
程序员文章站
2022-04-30 22:49:20
...
查找一个有序数组中的某个元素
void main()
{
int a[103];
//创建一个有序的数组
for (int i = 0; i < 103; i++)
{
a[i] = i;
}
int num = 52; //需要查找的元素
int shang = 0;
int xia = 102;
int zhong;
while (shang < xia)
{
zhong = (shang + xia) / 2;
printf("shang = %d,zhong = %d,xia = %d\n", shang, zhong, xia);
if (a[zhong] == num )
{
printf("找到了");
break;
}
else if (a[zhong] > num)
{
xia = zhong - 1;
}
else //a[zhong] < num
{
shang = zhong + 1;
}
}
system("pause");
}
上一篇: C语言实现字符串循环左移和右移
下一篇: 二分法查找