C++实现B-树插入删除查找

本文详细探讨了如何使用C++实现B-树的基本操作,包括插入、删除和查找算法。通过实例解析,深入理解B-树的数据结构及其在实际应用中的价值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*
 * BMT.h
 *
 *  Created on: Nov 2, 2015
 *      Author: chris
 */

#ifndef BMT_H_
#define BMT_H_

#include<iostream>

#define m 3

struct Record{
	//empty.
};

typedef int KeyType;

typedef struct BMTNode{
	int keynum;
	BMTNode * parent;

	KeyType   key[m+1];
	BMTNode * ptr[m+1];

	BMTNode(): keynum(0), parent(NULL) {
		for(int i = 0; i <= m; ++i) {
			key[i] = 0;
			ptr[i] = NULL;
		}//endfor
	}//endctor
}*BMT;

bool BMTSearchKey(BMT & T, KeyType K, BMTNode*& recNode, int &recIdx);
bool BMTInsertKey(BMT & T, KeyType K);
bool BMTDeleteKey(BMT & T, KeyType K);
void BMTDestroy(BMT & T);
void BMTWalkThrough(BMT & T);

#endif /* BMT_H_ */



/*
 * BMT.cpp
 *
 *  Created on: Nov 2, 2015
 *      Author: chris
 */

#include"BMT.h"
#include<iostream>
#include<cstdlib>

using namespace std;

int BMTSearch(BMT & T, KeyType K)
{
	int i = 0;
	for(int j = 1; j <= T->keynum; ++j)
		if(T->key[j] <= K) i = j;
	return i;
}

bool BMTSearchKey(BMT & T, KeyType K, BMTNode*& recNode, int &recIdx)
{
	recIdx = 0;
	recNode = NULL;

	BMTNode * curNode = T;
	while(curNode) {
		// search
		recIdx = BMTSearch(curNode, K);

		if (recIdx > 0 && curNode->key[recIdx] == K) {
			recNode = curNode;
			return true; //found
		} else {
			recNode = curNode;         // q: the parent of p
			curNode = curNode->ptr[recIdx]; // p->key[i]: the last key lt K
		} //endif
	} // endw
	return false;
}

void BMTInsert(BMT & T, int i, KeyType K, BMTNode* rhs)
{
	// T: current Tree Node;
	// i: points to the last elem that's le K;
	// K: the key to insert.
	// insert K to T->key[i+1] and rhs to T->ptr[i+1],

	// move backward
	for(int j = T->keynum; j >= i+1; --j) {
		T->key[j+1] = T->key[j];
		T->ptr[j+1] = T->ptr[j];
	}//endfor j

	T->key[i+1] = K;
	T->ptr[i+1] = rhs;
	++T->keynum;
}

bool BMTSplit(BMT & T, int s, BMT& rhs, KeyType& midK)
{
	// split T at s, with the right hand side stored in rhs
	// return key[s] by K.
	rhs = new BMTNode;
	if(!rhs) return false;
	rhs->parent = T->parent;

	// take out the mid node.
	midK = T->key[s];
	T->key[s]
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值