【发布时间】:2012-07-29 21:07:19
【问题描述】:
我目前正在从事一个分析项目,我正在观察在 Java 中实现不同算法时的行为方式。我从网上得到了一些实现 Mergesort 算法的代码,现在我需要在一个由 10,000 个随机生成的整数(介于 1 到 100,000 之间)组成的数组上运行此代码,并记录进行了多少交换和比较。
我不确定在代码中的哪一点增加计算交换和比较的变量。期望值是多少?由于 Mergesort 的最佳、最差和平均情况都是 nlog(n),这是否意味着我应该期望交换和比较的总和为 10,000*(log base 2 of 10,000) 大约 = 138,000?
这是代码,我猜只有在更改原始数组时才会发生交换,比较我不太确定:
void MergeSort(int low, int high)
// a[low : high] is a global array to be sorted.
// Small(P) is true if there is only one element to
// sort. In this case the list is already sorted.
{
if (low < high) { // If there are more than one element
// Divide P into subproblems.
// Find where to split the set.
int mid = (low + high)/2;
// Solve the subproblems.
MergeSort(low, mid);
MergeSort(mid + 1, high);
// Combine the solutions.
Merge(low, mid, high);
}
}
void Merge(int low, int mid, int high)
// a[low:high] is a global array containing two sorted
// subsets in a[low:mid] and in a[mid+1:high]. The goal
// is to merge these two sets into a single set residing
// in a[low:high]. b[] is an auxiliary global array.
{
int h = low, i = low, j = mid+1, k;
while ((h <= mid) && (j <= high)) {
if (a[h] <= a[j]) { b[i] = a[h]; h++; }
else { b[i] = a[j]; j++; } i++;
}
if (h > mid) for (k=j; k<=high; k++) {
b[i] = a[k]; i++;
}
else for (k=h; k<=mid; k++) {
b[i] = a[k]; i++;
}
for (k=low; k<=high; k++) a[k] = b[k];
}
【问题讨论】:
-
您好!每个 if() 语句都是比较,如果你说 b[i] = a[k],它就是一个交换。您需要计算这些操作执行了多少次。
-
while 或 for 循环中的操作是否也算作比较?例如,如果你有 while(i
0) 每次循环时都会算作比较吗?事实上,它是否算作两次比较,因为如果第一个不为假,您可能需要同时评估它们?