基本算法(3)—— 顺序查找和二分查找(折半查找)
- 没有排序的数据:只能顺序查找,速度慢
- 排序后的数据:二分查找
顺序查找
暴力破解法,按照顺序遍历整个数组,查找目标数据。
#include <iostream>
using namespace std;
int SequentialSearch(int *a, int n,const int x); //输入的数组,数组个数,要寻找的数
int main() {
int m[] = { 2,4,6,8,0,1,3,5,7,9 };
int result;
result = SequentialSearch(m, 10, 7);
if (result == -1) cout << "cannot find the number." << endl;
else cout << "it is found in m[" << result << "]." << endl;
return 0;
}
int SequentialSearch(int *a, int n, const int x) {
int i;
for (i = 0; i < n; i++) {
if (a[i] == x)
return i;
}
if (i == n) return -1;
}
二分查找
-
220 = 100万(1M)——100万个数据用二分查找只需要20次。
230 = 10亿(1G)
只需要查找log2n次.
-
必须数据已经排序!
#include <iostream>
using namespace std;
int BinarySearch(int* a, const int x,const int n); //数组,要查找的数,数组元素个数
int main()
{
int x[] = { 0,1,3,4,5,6,7,9 };
int result;
int num = 7;
result = BinarySearch(x, num, 8);
if (result < 0)
cout << "cannot find the num." << endl;
else
cout << "it is found in x[" << result << "]." << endl;
return 0;
}
int BinarySearch(int* a, const int x, const int n) {
int low, high, mid;
low = 0;
high = n - 1;
while (low <= high) {
mid = (low + high) / 2;
if (a[mid] == x) return mid;
else if (a[mid] < x) low = mid + 1;
else if (a[mid] > x) high = mid - 1;
else return -1; //没找到
}
}