【发布时间】:2017-10-02 18:59:10
【问题描述】:
给你int[][] lists(一个排序的整数数组)。
你要合并所有这些。
时间复杂度是多少?
我尝试通过将数组分成对并并行合并所有对来做到这一点。
public static List<Integer> merge(int[][] array) throws InterruptedException {
// number of array remaining to be merged
int remaining = array.length;
while (remaining > 2) {
List<Thread> threads = new LinkedList<>();
for (int i = 0; i < remaining - 1; i += 2) {
// DoMerge is a runnable that merges
// two array in O(n1 + n2) time (n1 and n2 are
// lengths of the two given arrays)
// DoMerge will also put the merged array
// at position i in the given array
Thread mergeThread = new Thread(new DoMerge(i, i + 1, array));
threads.add(mergeThread);
mergeThread.start();
}
// wait for them all to finish
for (Thread t : threads) {
t.join();
}
// move the newly merged list to the front
for (int j = 1, i = 2; i < remaining; i += 2, ++j) {
array[j] = array[i];
array[i] = null;
}
remaining = (int) Math.ceil(remaining / 2.0);
}
return combine(lists[0], lists[1]);
}
(假设处理器数量 >= arrays.length)
我认为这个时间复杂度是 log(n).k 其中 k 是要合并的每个数组的最大长度,n 是数组的数量。
这对吗?
【问题讨论】:
-
你是说 DoMerge 的 O(n1+n2) 吗?你写了 O(n1*n2)。
-
是的,“n1+n2”,对不起,错字
-
如果您在 non-deterministic Turing machine 上运行代码,那么 O(log(n) k) 是正确的(它可以并行运行无限数量的线程并且没有创建新线程的开销。 ) 当然,在真机上,一旦线程数大于物理 CPU 数,您很快就会遇到瓶颈,之后我们将回到 O(log(n) n) 渐近时间复杂度。
标签: algorithm merge parallel-processing time-complexity