小编han*_*ku8的帖子

线性搜索与二进制搜索效率

我目前正在研究不同的搜索算法,并且做了一些程序来看看效率上的差异。二进制搜索应该比线性搜索更快,但是时间的确显示了其他情况。我在代码中犯了一些错误还是这是一种特殊情况?

#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)

c++ algorithm performance search binary-search

2
推荐指数
2
解决办法
172
查看次数

标签 统计

algorithm ×1

binary-search ×1

c++ ×1

performance ×1

search ×1