【发布时间】:2013-05-07 00:01:25
【问题描述】:
我似乎不知道在 Merge 类中将比较计数器放在哪里。尽管它对数组进行了完美的排序,但它不会计算它进行的交换(或比较)的次数。请帮助这是我最终项目的一部分
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 的任务相比,放置
comparisons的位置是微不足道的 -
还请记住,仅仅因为您缩进了,并不意味着代码会在没有正确括号的情况下执行。你的 else 缺少括号。
标签: java sorting comparison mergesort