确定堆创建函数的时间复杂度(Big-O)。

huangapple go评论72阅读模式
英文:

Determine Big-O of heap creation function

问题

以下是翻译好的部分:

这个 heapify 方法的时间复杂度的大O表示是多少?我原以为是 O(log n),但好像不太对?如何使它变成 O(log n)?

假设我们有以下代码:

int arr[] = {1, 3, 5, 2, 7, 9, 4, 6};
int n = arr.length;
int i = 0; // 起始位置

void heapify(int arr[], int n, int i) {
    int largest = i;
    int left = 2 * i + 1;
    int right = 2 * i + 2;

    if (left < n && arr[left] > arr[largest]) {
        largest = left;
    }

    if (right < n && arr[right] > arr[largest]) {
        largest = right;
    }

    if (largest != i) {
        int swap = arr[i];
        arr[i] = arr[largest];
        arr[largest] = swap;

        heapify(arr, n, largest);
    }
}
英文:

What is the Big-O notation of this heapify method? I was expecting O(log n) but it does not add up? How do I make it O(log n)?

Assuming we have this:

int arr[] = {1, 3, 5, 2, 7, 9, 4, 6};
int n = arr.length;
int i = 0; // Start position



void heapify(int arr[], int n, int i) {
        int largest = i;
        int left = 2 * i + 1;
        int right = 2 * i + 2;

        if(left &lt; n &amp;&amp; arr[left] &gt; arr[largest]) {
            largest = left;
        }

        if(right &lt; n &amp;&amp; arr[right] &gt; arr[largest]) {
            largest = right;
        }

        if(largest != i) {
            int swap = arr[i];
            arr[i] = arr[largest];
            arr[largest] = swap;

            heapify(arr, n, largest);
        }
    }

Thanks,

答案1

得分: 1

这已经是 O(log n)。i 的值在每次递归调用时至少加倍,当 i >= n 时停止,在第一次调用后,i 至少为 1,因此递归调用最多可以有 O(log n) 次。

英文:

This is already O(log n). The value of i at least doubles with every recursive call, and when i &gt;= n it stops, and after the first call i is at least one, so there can be at most O(log n) recursive calls.

huangapple
  • 本文由 发表于 2020年10月8日 03:58:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64251471.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定