【问题标题】:Iterative MergeSort Time Complexity (Bottom-Up)迭代合并排序时间复杂度(自下而上)
【发布时间】:2017-04-02 13:05:47
【问题描述】:

我无法找到时间复杂度。

  • 首先,谈到 MergeSort 中的外部 FOR,我认为重复是 (1+ Sumation(from i=1, to sizeOfArray)(2*i) = 1+(2+4+8+16+32 +...+size) 但我也认为我错了。
  • 我在测量内部 FOR 循环重复时也遇到了问题。

MergeSort(){ //迭代版本(自下而上)

            for(int currentSize = 1; currentSize < length; currentSize *= 2)        {
                for(int low = 0; low < length - currentSize; low += 2*currentSize){

                    int mid = low + currentSize - 1;
                    //min() is used here so if low is very close to the end of the array, high doesn't take outOfBoundries Value.
                    int high = Math.min(low + currentSize*2 -1, length - 1);

                }
            }

}

合并(int low,int middle,int high){

            // Copy both parts into the helper array
            for (int i = low; i <= high; i++) {
                    helper[i] = arrayForMergeSort[i];
            }

            int i = low;
            int j = middle + 1;
            int k = low;
            // Copy the smallest values from either the left or the right side back
            // to the original array
            while (i <= middle && j <= high) {
                    if (helper[i] <= helper[j]) {

                            arrayForMergeSort[k] = helper[i];
                            i++;
                    } else {

                            arrayForMergeSort[k] = helper[j];
                            j++;
                    }
                    k++;
            }
            // Copy the rest of the left side of the array into the target array
            while (i <= middle) {
                    arrayForMergeSort[k] = helper[i];
                    k++;
                    i++;
            }

    }

【问题讨论】:

    标签: sorting time-complexity mergesort


    【解决方案1】:

    对于外循环,迭代次数为ceil(log2(length))。

    对于内部循环,每次迭代要合并的运行次数为 ceil(length / currentSize) 或 floor((length + currentSize - 1) / currentSize)。如果这是一个偶数,那么最后一次运行的大小可能小于 currentSize。如果这是一个奇数,则最后一次运行没有要合并的运行,也可能小于当前大小。我不确定是否有一种方法可以计算合并操作的总数,而不使用迭代来对每次迭代的合并操作求和。

    在合并排序的“生产”版本中,一次性分配与原始数组大小相同(或 1/2)的工作数组,然后是合并方向(原始到工作或工作每次外循环都会改变 to original. 如果程序预先计算了外迭代的次数,并且它是奇数,则可以进行预遍历以在初始遍历时将元素交换到位,以便偶数完成了多次合并,排序后的数据最终在原始数组中。

    【讨论】:

    • 所以我最终发现外部for循环的重复是C(n)= log(n)。并且内部 for 循环执行 n/log(n) 次重复,因此我们总共有 n 次重复。如我错了请纠正我。所以我们有 n 次在 Theta(n) 中运行的合并函数。那么总复杂度是多少?
    • 假设一个典型的归并排序,内循环每次迭代总是移动n个元素,所以移动的总数是(内乘外循环)n log(n)。每个内部循环的最坏情况比较数是 n-1,如果合并两个大小为 n/2 的运行,最好情况是 n/2 比较,因此比较的大 O 时间复杂度是 O(n log(n)),因为常量被忽略了。
    猜你喜欢
    • 1970-01-01
    • 2020-08-08
    • 2012-05-07
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    • 2019-05-09
    相关资源
    最近更新 更多