我有一个使用BST对数组进行排序的函数。首先,我使用for循环和函数插入创建树(在树中插入数据保持有序) 然后我按顺序访问树并在排序模式下将每个节点复制到一个新的临时存档中。 这是我的代码:
double btree_sort(SPerson Archive[], unsigned int ne, double *btree_creating_time)
{
int i = 0;
TBinaryTree BinaryTree = NULL;
cont = 0;
LARGE_INTEGER freq;
LARGE_INTEGER t0, tF, tDiff;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&t0);
/*Algorithm*/
for (i = 0; i < ne; i++) /*Creating B-Tree*/
BinaryTree = binarytree_insert(BinaryTree, Archive[i]);
QueryPerformanceCounter(&tF);
tDiff.QuadPart = tF.QuadPart - t0.QuadPart;
*btree_creating_time = tDiff.QuadPart / (double)freq.QuadPart;
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&t0);
inorder(BinaryTree, Archive);
/*end*/
QueryPerformanceCounter(&tF);
tDiff.QuadPart = tF.QuadPart - t0.QuadPart;
free(BinaryTree);
return tDiff.QuadPart / (double)freq.QuadPart;
}
int inorder(TBinaryTree BinaryTree, SPerson Archive[])
{
if (BinaryTree)
{
inorder(BinaryTree->left,Archive);
swap(&Archive[cont++], &BinaryTree->information);
inorder(BinaryTree->right, Archive);
}
return 1;
}
TBinaryTree binarytree_insert(TBinaryTree bt, SPerson to_add)
{
if (bt == NULL)
{
TNode *new_node = create_node(to_add);
if (new_node == NULL)
{
MessageBoxA(0, "Error allocating memory.", "", 0);
exit(1);
}
return new_node;
}
else
{
if (strcmp(to_add.id, bt->information.id)<0)
{
bt->left = binarytree_insert(bt->left, to_add);
return bt;
}
else
{
bt->right = binarytree_insert(bt->right, to_add);
return bt;
}
}
}
考虑一下:
在最佳情况下插入b树具有Θ(1)的时间复杂度,在最差情况下具有Θ(nlogn)。 (无论如何是写Θ的权利,或者我应该说O是最好的情况而Ω应该是最差的?)
有序vist的时间复杂度为Θ(n)
因此,在树中插入n个元素,访问和交换时间复杂度为:
最佳案例:[仅一个元素]Θ(1)+ [Θ(1)+Θ(4)] [交换函数时间复杂度]
最坏情况:Θ(nlogn)+ [Θ(n)+Θ(4)]
我是对的吗?有什么建议?提前谢谢。
答案 0 :(得分:5)
最糟糕的案例复杂性称为O - Big Oh表示法。我们通常只使用最坏的情况复杂性。 Btree中所有节点的插入也是O(nlogn)。因此,对树进行排序是插入所有键,然后遍历具有O(n)复杂度的树。
因此整体复杂度为O(nlogn)+ O(n)即O(nlogn)
答案 1 :(得分:1)
在二叉搜索树上插入操作的最坏情况时间复杂度为O(logn)。插入n个数字将是O(nlogn)。接着遍历所有n个节点的O(n)。因此O(nlogn)+ O(n)是O(nlogn)。