マージソート中に発生したスワップと比較の数を数える必要があります。比較数のカウントは問題ないと思います。再帰のために、配列の長さと同じ数の数を取得します。どういうわけか、それらの数をマージソート関数の変数に格納する必要がありますか?また、合計スワップをカウントする方法についてのアイデアを知りたいです
void merge(double arr[], int l, int m, int r)
{
int counter = 0;//number of comparisons
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int cc;
/* create temp arrays */
double L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
counter++;
}
cout << counter << endl;
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(double arr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l+(r-l)/2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
これは@JerryCoffinの回答に似ていますが、消化するのが少し簡単かもしれません。
簡単な解決策は、このコードをクラスint swapcount
に配置し、スワップが実行されるたびにインクリメントする、と呼ばれることもあるメンバー変数を用意することです。これにより、ローカルスワップカウンター変数を維持する必要がなくなります。
class MergeSorter
{
int swapCount;
void merge(double arr[], int l, int m, int r);
void mergeSort(double arr[], int l, int r);
public:
MergeSorter() : swapCount(0) { }
void startSort(double arr[], int l, int r);
int getSwapCount() const { return swapCount; }
};
void MergeSorter::merge(double arr[], int l, int m, int r)
{
// code here to merge. In here, you increment swapCount
}
void MergeSorter::mergeSort(double arr[], int l, int r)
{
if (l < r)
{
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
void MergeSorter::startSort(double arr[], int l, int r)
{
swapCount = 0; // start at 0
mergeSort(arr, l, r);
}
int main()
{
double arr[] = {1, 2, 3, 45, 5, 7};
MergeSorter ms;
ms.startSort(arr, 0, 5); // or whatever the arguments are
std::cout << "The number of swaps is " << ms.getSwapCount();
}
startSort
クラス内でソートを開始する関数があることに注意してください。ではmerge
機能、swapCount
必要に応じて増加します。最後に、の値を出力するだけですms.swapCount
。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加