BST花费更少的时间来获得更大的输入

时间:2015-02-12 11:41:29

标签: c++ data-structures time timer binary-search-tree

以下程序会插入BST。

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <sys/time.h>

using namespace std;

struct node {
    long long int val;
    struct node *left;
    struct node *right;
};

struct node *insert(struct node *root, long long int x) {
    if (root == NULL) { 
        struct node *newnode = (struct node *) malloc(sizeof(struct node));
        newnode->right = NULL;
        newnode->left = NULL;
        newnode->val = x;
        root = newnode;
        return root;
    } else {
        if (root->val > x) {
            root->left = insert(root->left, x);
        } else if (root->val < x) {
            root->right = insert(root->right, x);
        }
    }
    return root;
}

int main()
{
    srand(clock());

    long long int n;
    long long int i;
    long long int j;

    for (j = 1; j <= 100; j++) {
            struct timeval strt_time, stop_time;
        double delay;

        cin >> n;
        struct node *root = NULL;
                gettimeofday(&strt_time, NULL);
        for (i = 1; i <= n; i = i * 10) {
            long long int x = (rand() % 1000);
            root = insert(root, x);
        }
                gettimeofday(&stop_time, NULL);

                delay = (stop_time.tv_sec - strt_time.tv_sec) * 1000.0;
                delay += (stop_time.tv_usec - strt_time.tv_usec) / 1000.0;

                printf("%10lld => %9.3f \n", n, delay);
    }

    return 0;
}

这是我的输出,其中l.h.s是随机生成的节点数,r.h.s是插入指定节点数所需的时间。

1000 =>        0.105
2000 =>        0.004    
3000 =>        0.003    
10000 =>       0.004    
1000000 =>     0.004    
2000000 =>     0.004    
10000000 =>    0.005    
100000000 =>   0.005 

当插入的节点数量更多时,为什么时间会减少?

0 个答案:

没有答案