二分查找适用于已经排好序的数组,二分查找的平均(时间)复杂度远比顺序查找要小得多,在庞大的数据中更明显。 二分查找:
#include <cstdio>
#include <iostream>
int main() {
int a
[10] = {11, 22, 33, 44, 55, 66, 77, 88, 99, 100}, mid
, L
, R
, s
= 55;
L
= 0;
R
= 9;
while (L
<= R
) {
mid
= L
+ (R
- L
) / 2;
if (s
> a
[mid
])
L
= mid
+ 1;
else if (s
< a
[mid
])
R
= mid
- 1;
else {
printf("%d\n", mid
);
system("pause");
return 0;
}
}
printf("didn't find!\n");
return 0;
}
转载请注明原文地址:https://ipadbbs.8miu.com/read-1222.html