【发布时间】:2014-06-27 17:55:05
【问题描述】:
我在做 DSA(数据结构和算法)作业时偶然发现了一个问题。据说我用插入和搜索算法实现了一个 B-Tree。就目前而言,搜索工作正常,但我在实现插入功能时遇到了麻烦。特别是 B-Tree 节点分裂算法背后的逻辑。我可以想出的伪代码/C 风格如下:
#define D 2
#define DD 2*D
typedef btreenode* btree;
typedef struct node
{
int keys[DD]; //D == 2 and DD == 2*D;
btree pointers[DD+1];
int index; //used to iterate throught the "keys" array
}btreenode;
void splitNode(btree* parent, btree* child1, btree* child2)
{
//Copies the content from the splitted node to the children
(*child1)->key[0] = (*parent)->key[0];
(*child1)->key[1] = (*parent)->key[1];
(*child2)->key[0] = (*parent)->key[2];
(*child2)->key[1] = (*parent)->key[3];
(*child1)->index = 1;
(*child2)->index = 1;
//"Clears" the parent node from any data
for(int i = 0; i<DD; i++) (*parent)->key[i] = -1;
for(int i = 0; i<DD+1; i++) (*parent)->pointers[i] = NULL
//Fixed the pointers to the children
(*parent)->index = 0;
//the line bellow was taken out for creating a new node that didn't have to be there.
//(*parent)->key[(*parent)->index] = newNode(); // The newNode() function allocs and inserts a the new key that I need to insert.
(*parent)->pointers[index] = (*child1);
(*parent)->pointers[index+1] = (*child2);
}
我几乎可以肯定我的指针搞砸了,但我不确定是什么。任何帮助表示赞赏。也许我需要对 B-Tree 主题进行更多研究?我必须补充一点,虽然我可以使用 C++ 的基本输入/输出,但我需要使用 C 风格的结构。
【问题讨论】:
-
你可以使用类吗?
-
@Casey - 看看最后一行:
I must add that while I can use basic input/output from C++, I need to use C-style structs. -
技术上是的,但我对 OOP 几乎一无所知。我的意思是,我可以阅读和理解代码,但我不知何故缺乏编写 OOP 代码的知识。如果您有使用类的解决方案,我很乐意阅读。
-
@haneefmubarak 没关系,但感谢您的关注!
标签: c++ c algorithm data-structures b-tree