- 作者:邹祁峰
- 邮箱:[email protected]
- 博客:http://blog.csdn.net/qifengzou
- 日期:2014.03.13 18:00
- 转载请注明来自"祁峰"的CSDN博客
1 引言
In computer science, a B-tree is a tree data structure that keeps data sorted and allows searches, sequential access, insertions, and deletions in logarithmic time. The B-tree is a generalization of a binary search tree in that a node can have more than two children (Comer 1979, p. 123). Unlike self-balancing binary search trees, the B-tree is optimized for systems that read and write large blocks of data. It is commonly used in databases and filesystems.
在计算机科学中,B树在查找、访问、插入、删除操作上时间复杂度为O(log2~n)(2为底数 n为对数),与自平衡二叉查找树不同的是B树对大块数据读写的操作有更优的性能,其通常在数据库和文件系统中被使用。
一棵m阶的B树,或为空树,或为满足下列特征的m叉树:
①、树中每个结点至多有m棵子树;
②、若根结点不是终端结点,则至少有2棵子树;
③、除根之外,所有非终端结点至少有棵子树;
④、所有的非终端结点中包含下列信息数据:
[n, C0, K0, C1, K1, C2, K2, ...., Kn-1, Cn]
其中:Ki[i=0,1,...,n-1]为关键字,且Ki<Ki+1[i=0, 1, ..., n-2];Ci[i=0,1,...,n]为至上子树根结点的指针,且指针Ci所指子树中所有结点的关键字均小于Ki[i=0,1,...,n-1],但都大于Ki-1[i=1,...,n-1];
2 编码实现
2.1 结构定义
根据m阶B树的性质,B树的相关结构定义如下:
/* B树结点结构 */typedef struct _btree_node_t{
int num; /* 关键字个数 */ int *key; /* 关键字:所占空间为(max+1) - 多出来的1个空间用于交换空间使用 */ struct _btree_node_t **child; /* 子结点:所占空间为(max+2)- 多出来的1个空间用于交换空间使用 */ struct _btree_node_t *parent; /* 父结点 */}btree_node_t;
代码1 结点结构
/* B树结构 */typedef struct{
int max; /* 单个结点最大关键字个数 - 阶m=max+1 */ int min; /* 单个结点最小关键字个数 */ int sidx; /* 分裂索引 = (max+1)/2 */ btree_node_t *root; /* B树根结点地址 */}btree_t;
代码2 B树结构
2.2 创建B树
此过程主要是完成btree_t中最大关键字个数max、最小关键字个数min、分裂索引sidx的设置,并创建一颗空树,为后续的构造B树做好准备条件。
/****************************************************************************** **函数名称: btree_creat **功 能: 创建B树 **输入参数: ** _btree: B树 ** m: 阶 - 取值范围m>=3 **输出参数: NONE **返 回: 0:成功 -1:失败 **实现描述: **注意事项: ** 注意:参数max的值不能小于2. **作 者: # Qifeng.zou # 2014.03.12 # ******************************************************************************/int btree_creat(btree_t **_btree, int m){ btree_t *btree = NULL; if(m < 3) { fprintf(stderr, "[%s][%d] Parameter 'max' must geater than 2.\n", __FILE_