任意输入一个数,在一个数组中看看能不能找到找出这个数
第一种不采用函数调用
代码如下:
#include<iostream>
using namespace std;
int main()
{
int a[6] = { 1,2,3,4,5,6 };
int x;
int i, top, mid, bot, find;
top = 5;
bot = 0;
find = 0;
//进行多次查找
while (1)
{
cout << "输入你要查找的数" << endl;
cin >> x;
while (bot <= top)
{
mid = (top + bot) / 2;
if (x == a[mid])
{
find = 1;
printf("find:%d,it is a[%d]\n", x, mid);
cout << "it is a[" << mid << "]" << endl;
break;
}
else if (x < a[mid])
{
top = mid - 1;
}
else
{
bot = mid + 1;
}
}
if (!find)
{
cout << "未找到" << endl;
}
//进行多次查找把每次的top、bot,find 重新赋值,若果只是一次,那么没必要加
top = 5;
bot = 0;
find = 0;
}
system("pause");
}
第二种采用函数的调用,和第一种差不多,主要的确定范围的while循环
#include <iostream>
using namespace std;
void zhebanSearch(int x, int a[], int n)
{
int bot, top, mid;
bot = 0;
top = n - 1;
top = n - 1;
int find = 0;
while (bot <= top)
{
mid = (top + bot) / 2;
if (x == a[mid])
{
find = 1;
cout << "it is a[" << mid << "]" << endl;
break;
}
else if (x < a[mid])
{
top = mid - 1;
}
else
{
bot = mid + 1;
}
}
if (!find)
{
cout << "未找到" << endl;
}
}
int main()
{
int arr[6] = { 1,2,3,4,5,6 };
cout << "请输入要查找的数"<<endl;
int x;
cin >> x;
zhebanSearch(x,arr,6);
return 0;
}