我似乎無法弄清楚我的比較計數器放在合併類的位置。雖然它完美地對數組進行排序,但它不會計算它所做交換(或比較)的次數。請幫助,這是我的除了最後的項目合併排序比較計數器
public static int mergeSort(int[] intArray, int first, int last) {
if(first < last) {
int mid = (first + last)/2;
mergeSort(intArray, first, mid);
mergeSort(intArray, mid + 1, last);
Merge(intArray, first, mid, last);
}
return comparisons;
}
public static int Merge(int[] intArray, int first, int mid, int last) {
//int count = 0;
comparisons = 0;
int first1 = first, last1 = mid;
int first2 = mid + 1, last2 = last;
int temp[] = new int[intArray.length];
int index = first1;
while(first1 <= last1 && first2 <= last2) {
if(intArray[first1] < intArray[first2]) {
temp[index] = intArray[first1++];
comparisons++;
}
else
temp[index] = intArray[first2++];
index++;
comparisons++;
}
while(first1 <= last1)
temp[index++] = intArray[first1++];
while(first2 <= last2)
temp[index++] = intArray[first2++];
for(index = first; index <= last; index++)
intArray[index] = temp[index];
return comparisons;
}
你從別人複製這個代碼?與編寫mergeSort – 2013-05-07 00:03:24
的任務相比,放置「比較」的地方是微不足道的。還記得僅僅因爲您縮進,並不意味着代碼將會在沒有正確括號的情況下執行。你的其他人缺少parens。 – greedybuddha 2013-05-07 01:27:20