我目前正在研究一個分析項目,我正在觀察在Java中實現時不同算法的行爲。我得到了一些代碼,它實現了在線的Mergesort算法,現在我需要在10,000個隨機生成的整數(1到100,000)的數組上運行這個代碼並記錄進行了多少次交換和比較。Mergesort互換和比較
我不太確定代碼中的哪一點增加計數交換和比較的變量。預期的價值是多少?因爲Mergesort的最好,最差和平均情況都是nlog(n),這是否意味着我應該期望10,000 *(10,000的基數爲2)約爲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],它就是交換。你需要數,這些操作執行多少次。 – 2012-07-29 21:31:52
while或for循環中的操作是否也算作比較?例如,如果你有(while)(i 0),那麼它每次循環時都會作爲比較計數嗎?事實上,它是否被視爲兩個比較,因爲如果第一個不是錯誤的,你可能需要對它們進行評估? –
Mike
2012-07-29 22:11:42