顺序查找和二分查找
程序员文章站
2024-03-17 17:01:52
...
顺序查找。(待完善如果有相同的数值???该怎么查找)
#include <iostream>
using namespace std;
int f1(int A[], int n, int find)
{
int i = 0;
for (i = 0; i <= 9; i++)
if (A[i] == find) return i;
return -1;
}
int main()
{
int a[10];
int i;
for (i = 0; i <= 9; i++)cin >> a[i];
int find;
cin >> find;
if (f1(a, 10, find) >= 0) cout << "找的的数为a[" << f1(a, 10, find) << "]" << endl;
else cout << "未找到" << endl;
return 0;
}
二分查找
#include <iostream>
using namespace std;
int f1(int A[], int n, int find)
{
int a, b, m;
a = 0;
b = n - 1;
while (a <= b)
{
m = a + (b - a) / 2;
if (A[m] > find)b = m - 1;
else if (A[m] < find)a = m + 1;
else return m;
}
return -1;
}
int main()
{
int a[10];
int i;
cout << "从小到大输入一组数" << endl;
for (i = 0; i <= 9; i++)cin >> a[i];
int find;
cout << "输入要找的值" << endl;
cin >> find;
int x = f1(a, 10, find);
if (x >= 0)cout << "要找的值的为a[" << x << "]" << endl;
else cout << "不存在要找的数" << endl;
return 0;
}