私は次のMergeSortクラスを持っています。私は比較とスワップのカウンターを実装する必要があります。私の比較とスワップカウンターが正しい場所にあるかどうか確認してもらえますか?Java MergeSort:比較とスワップカウンタ
ご覧のとおり、スワップカウンタと比較カウンタの2つのクラスプロパティがあります。私が正確にポジティブではないところは、A)swapCountとcompareCount(runSortメソッドまたはmergeSortメソッドで)を初期化し、B)マージメソッドのswapCount ++をどこに配置するかです。私は確かにcompareCount ++が正しい場所にあると確信しています。
ここにコードがあります。返信したすべての人に事前に感謝!
public class MyMergeSort {
private int swapCount;
private int compareCount;
public void runSort() {
//this.compareCount = 0;
//this.swapCount = 0;
mergeSort(this.sortItems,0,sortItems.length);
}
public void mergeSort(String[] data, int first, int n) {
int n1; // Size of the first half of the array
int n2; // Size of the second half of the array
this.compareCount = 0;
this.swapCount = 0;
if (n > 1) {
// Compute sizes of the two halves
n1 = n/2;
n2 = n - n1;
mergeSort(data, first, n1); // Sort data[first] through data[first+n1-1]
mergeSort(data, first + n1, n2); // Sort data[first+n1] to the end
// Merge the two sorted halves.
merge(data, first, n1, n2);
}
}
private void merge(String[] data, int first, int n1, int n2) {
String[] temp = new String[n1+n2]; // Allocate the temporary array
int copied = 0; // Number of elements copied from data to temp
int copied1 = 0; // Number copied from the first half of data
int copied2 = 0; // Number copied from the second half of data
int i; // Array index to copy from temp back into data
// Merge elements, copying from two halves of data to the temporary array.
while ((copied1 < n1) && (copied2 < n2)) {
compareCount++;
if (data[first + copied1].compareTo(data[first + n1 + copied2]) < 0) {
temp[copied++] = data[first + (copied1++)];
//swapCount++;
}
else {
temp[copied++] = data[first + n1 + (copied2++)];
swapCount++;
}
}
// Copy any remaining entries in the left and right subarrays.
while (copied1 < n1)
temp[copied++] = data[first + (copied1++)];
while (copied2 < n2)
temp[copied++] = data[first + n1 + (copied2++)];
// Copy from temp back to the data array.
for (i = 0; i < n1+n2; i++)
data[first + i] = temp[i];
}
}
**更新2011/11/28 **良いニュース。私は最終的に私が探していただけのものを見つけたと思う:
http://www.cs.carleton.edu/faculty/adalal/teaching/f04/117/notes/nov08/Sort.java
そのコードの作者に大きな感謝を!
あなたのカウントを 'runSort'で初期化する必要があります。 'mergeSort'でそれらを初期化すると、すべての再帰呼び出しでそれらを上書きします。 – teppic
おかげです。そして私は、信憑性のある情報源であると思われるものからさらに正しい方向へ私をさらに向ける何かを見つけたと思うと思う: http://www.cs.carleton.edu/faculty/adalal/teaching/f04/117/notes/nov08 /Sort.java – 72909903