【发布时间】:2018-11-12 20:42:22
【问题描述】:
假设我们有以下 b-tree
我想创建一个算法来找到第 k 个最小的元素。我尝试实现link 中所写的内容,但我发现似乎没有一个解决方案适用于这种树。
到目前为止我已经做到了,这对于最后一个分支的元素运行良好
i <-0
function kthSmallestElement(Node node, int k)
if(branch[i] != NULL) then
size<-branch[i].size();
if(k < size) then
i++;
call the function recursively for new branch[i], k
else if(k > size) then
k-=size
i++;
call the function recursively for new branch[i], k
else if (k==size) then
print branch[i]->entry[k-1]
else
print brach[i-1]->entry[k-1]
end function
我已经使用 C 实现了算法
#define MAX 4 /* maximum number of keys in node. */
#define MIN 2 /* minimum number of keys in node */
typedef int Key;
typedef struct {
Key key;
int value; /* values can be arbitrary */
} Treeentry;
typedef enum {FALSE, TRUE} Boolean;
typedef struct treenode Treenode;
struct treenode {
int count; /* denotes how many keys there are in the node */
/*
The entries at each node are kept in an array entry
and the pointers in an array branch
*/
Treeentry entry[MAX+1];
Treenode *branch[MAX+1];
};
int i = 0;
int size = 0;
void FindKthSmallestElement(Treenode *rootNode, int k){
if(branch[i] != NULL) //since the node has a child
size = branch[i] ->count;
if(k < size){
i++;
FindKthSmallestElement(branch[i], k);
}else if(k > size){
k-=size;
i++;
FindKthSmallestElement(branch[i], k);
}else if (k==size)
printf ("%d", branch[i]->entry[k-1].key);
else
printf ("%d", brach[i-1]->entry[k-1].key);
}
您能否建议我应该解决什么问题才能为每个第 k 个最小的元素提供有效的输出?我倾向于认为这个问题不能递归解决,因为我们在每个节点中有多个条目。把它变成像link 这样的堆树是明智的吗?
【问题讨论】:
-
采用普通的b-tree排序算法并取第k个元素有什么问题?
-
请将其转换为minimal reproducible example,以证明您已取得的成就。
-
贴出的代码不是C,而是一些伪代码。您说它“对于最后一个分支的元素运行良好”。好的 - 但如果你有一些 C 代码,请发布它而不是伪代码。
-
由于该问题缺乏数据结构和代码等基本内容,因此任何人都很难为您提供帮助。如果数据结构和我想象的一样,那么可以使用递归,但你必须一直向下到左边开始,然后在函数调用开始返回时检查“返回值”。跨度>
-
@Simons0n 你说得有道理,我只是想知道我是否可以使用如上所示的算法递归地解决这个问题
标签: c algorithm data-structures b-tree