顺序查找与折半查找(二分查找)
没有排序的数据:只能顺序查找
已经排序的数据:二分查找即可
顺序查找:速度慢
例如:100万个数据,平均要找50万次!
#include<iostream>
using namespace std;
int SequentialSearch(int *a, const int n, const int x);
int main(){
int m[] = { 2, 4, 6, 8, 0, 1, 3, 5, 7, 9 };
int 结果;
int num = 7;
结果 = SequentialSearch(m, 10, num);
if (结果 == -1)
cout << "没找到!" << endl;
else
cout << "在m[" << 结果 << "]里找到" << num << endl;
system("pause");
return 0;
}
int SequentialSearch(int *a, const int n, const int x){
int i;
for (i = 0; i < n; i++){
//这里如果找到了,则返回下标。停止循环。
if (a[i] == x)
return i;
}
//如果没有找到,已经遍历了所有的数据
if (i == n) return -1;
}
总结:顺序查找是一种比较慢的方法,但是对于乱序的数据也没有其他方法可以处理。