我目前正在研究不同的搜索算法,并且做了一些程序来看看效率上的差异。二进制搜索应该比线性搜索更快,但是时间的确显示了其他情况。我在代码中犯了一些错误还是这是一种特殊情况?
#include <chrono>
#include <unistd.h>
using namespace std;
const int n=1001;
int a[n];
void assign() {
for (int i=0; i<n; i++) {
a[i]=i;
}
}
void print() {
for (int i=0; i<n; i++) {
cout << a[i] << endl;
}
}
bool find1 (int x) {
for (int i=0; i<n; i++) {
if (x==a[i]){
return true;
}
} return false;
}
bool binsearch(int x) {
int l=0,m;
int r=n-1;
while (l<=r) {
m = ((l+r)/2);
if (a[m]==x) return true;
if …Run Code Online (Sandbox Code Playgroud)