我目前正在从事一个分析项目,我正在观察在 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];
}