B- Tree 的实现

来源:互联网 发布:征途时间版源码 编辑:程序博客网 时间:2024/05/21 09:32
/* define B- tree node*/
#define M 10
typedef int KeyType;
typedef struct node
{
    struct node *parent;
    int count;
    KeyType key[M];
    struct node *ptr[M];
} BTNode;

typedef struct  
{
    BTNode *pt;
    int i;
    int tag;
} Result;

int Search(BTNode *pt, KeyType k)
{
    // search i: pt->key[i] <= k < pt->key[i+1]
    // think about i = 0 and i = pt->count
    for (int i=0; i < pt->count && pt->key[i+1] <= k; i++)
    {
        ;
    }
    return i;
}

Result SearchBTree(BTNode *t, KeyType k)
{
    BTNode *p = t, q = NULL;
    int found = 0, i = 0;
    Result r;
    
    while (p != NULL && found == 0)
    {
        /* p->key[i] <= k < p->key[i+1] */
        i = Search(t, k);
        if (i>0 && t->key[i] == k)
        {
            found = 1;
        }
        else
        {
            q = p;
            p = t->ptr[i];
        }        
    }

    r.i = i;
    if (found == 1)
    {
        r.pt = p;
        r.tag = 1;
    }
    else
    {
        r.pt = q;
        r.tag = 0;
    }
    return r;
}

// Insert x and ap at : i + 1. notice BTNode *&q
void Insert(BTNode *&q, int i, KeyType x, BTNode *ap)
{
    int j;
    for (j=q->count; j>i; j--)
    {
        q->key[j+1] = q->key[j];
        q->ptr[j+1] = q->ptr[j];
    }
    q->key[i+1] = x;
    q->ptr[i+1] = ap;

    if (ap != NULL)
    {
        ap->parent = q;
    }

    q->count++;
}

void Split(BTNode *&q, BTNode *&ap)
{
    ap = (BTNode *)malloc(sizeof(BTNode));
    int s = (m + 1) / 2;

    ap->ptr[0] = q->ptr[s];

    for (int i = s+1; i <= q->count; ++i) //q->count = m;
    {
        ap->key[i-s] = q->key[i];
        ap->ptr[i-s] = q->ptr[i];

        if (ap->ptr[i-s] != NULL)
        {
            ap->ptr[i-s]->parent = ap;
        }
    }
    ap->count = q->count - s;
    // add
    ap->parent = q->parent; // think?

    // repeat? 下面的这段好像跟上面的重复了
    for (int j = 0; j <= ap->count; ++j)  //  或者j = q->count - s;
    {
        if (ap->ptr[j] != NULL)
        {
            ap->ptr[j].parent = ap;
        }
    }

    q->count = s - 1;

}

B+树


原创粉丝点击