Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/qt/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 什么是堆排序';s递推关系?_Algorithm_Sorting_Time Complexity_Heapsort - Fatal编程技术网

Algorithm 什么是堆排序';s递推关系?

Algorithm 什么是堆排序';s递推关系?,algorithm,sorting,time-complexity,heapsort,Algorithm,Sorting,Time Complexity,Heapsort,我需要使用Master定理计算堆排序的时间复杂度,但我不知道哪个是递归关系。我知道它的复杂性是O(n logn),因为它遍历一个二叉树n次。但是我需要特别使用Master定理,对于它,我需要递推关系。堆排序的关系是什么?让我们从heapsort算法开始: heap_sort(int Arr[]) { int heap_size = n; build_maxheap(Arr); for(int i = n; i >= 2 ; i--) { s

我需要使用Master定理计算堆排序的时间复杂度,但我不知道哪个是递归关系。我知道它的复杂性是O(n logn),因为它遍历一个二叉树n次。但是我需要特别使用Master定理,对于它,我需要递推关系。堆排序的关系是什么?

让我们从heapsort算法开始:

heap_sort(int Arr[])
{
    int heap_size = n;

    build_maxheap(Arr);
    for(int i = n; i >= 2 ; i--)
    {
        swap(Arr[1], Arr[i]);
        heap_size = heap_size - 1;
        heapify(Arr, 1, heap_size);
    }
}
build_maxheap()函数有一个O(n)的标准实现

排序的重要部分是for循环,它执行n次。 里面有一个swap方法调用和heapify方法调用。 heapify方法是完整二叉树的标准遍历。因此,复杂性为O(logn)

T(n)=O(n)+n*O(对数n) =O(n*logn)

主定理对于解决许多分治算法的递推关系非常有用

现在,若你们对主定理的应用感兴趣。我们可以实现一个递归算法

heap_sort(int Arr[])
{
    int heap_size = n;
    build_maxheap(Arr);

    heap_sort_recurse(Arr, heap_size);

}

heap_sort_recurse(int Arr[], heap_size)
{
    swap(Arr[1], Arr[n]);
    heap_size = heap_size - 1;
    heapify(Arr, 1, heap_size);
}
在这种情况下,你可能有一个如下的递推方程

T(n)=T(n-1)+O(对数n)

显然,这不能用主定理直接解决。 有一个修正的公式推导出的减法和征服类型

这可能有用

对于形式的重复

T(n) = aT(n-b) + f(n)

where n > 1, a>0, b>0
如果f(n)是O(nk),k>=0,那么

  • 如果是a1,则T(n)=O(n*an/b)
  • 应用这个,

    我们有a=1,b=1,k=0

    因此,第二种情况适用。因此,

    T(n)=O(n0+1*logn) =O(n*logn)


    希望有帮助

    我明白了,非常感谢!但是我有一个问题,T(n)=T(n-1)+O(logn)Heapify的递归吗?它是针对heap\u sort\u recurse()的。在它里面我们有heapify()调用,它是O(logn)。Heapify有不同的递归T(n)=T(n/2)+O(1)类似于二进制搜索,因为它是树的遍历高度。它将根据主定理计算为O(logn)。