我认为在返回比较次数的合并排序 2 类/方法中使用合并排序的比较次数不正确。合并排序 2 类似于合并排序,但只返回比较的数量。下面是我的演示,我有一个包含 4 个整数 {2,55,1,45} 的数组,当我运行程序时它返回 8 个比较。谁能验证这是否正确或我做错了什么?
我的演示:
ArrayInts[] myInts2 = new ArrayInts[4];
myInts2[0] = new ArrayInts(2);
myInts2[1] = new ArrayInts(55);
myInts2[2] = new ArrayInts(1);
myInts2[3] = new ArrayInts(45);
MergeSort.mergeSort(myInts2, 0, 3);
System.out.println("Sorted using Merge Sort: ");
for (int index = 0; index < myInts2.length; index++) {
System.out.println(myInts2[index]);
}
System.out.println("Number of comps using Merge Sort: " + MergeSort2.mergeSort2(myInts2, 0, 3));
System.out.println(" ");
我的合并排序 2 类/方法:
public class MergeSort2 {
private static long comp=0;
public static <T extends Comparable<? super T>> long mergeSort2(T[] data, int min, int max) {
T[] temp;
int index1, left, right;
//return on list of length one
if (min == max) {
return comp;
}
//find the length and the midpoint of the list
int size = max - min + 1;
int pivot = (min + max) / 2;
temp = (T[]) (new Comparable[size]);
mergeSort2(data, min, pivot); //sort left half of list
mergeSort2(data, pivot + 1, max); //sort right half of list
//copy sorted data into workspace
for (index1 = 0; index1 < size; index1++) {
temp[index1] = data[min + index1];
}
//merge the two sorted lists
left = 0;
right = pivot - min + 1;
for (index1 = 0; index1 < size; index1++) {
comp++;
if (right <= max - min) {
if (left <= pivot - min) {
if (temp[left].compareTo(temp[right]) > 0) {
data[index1 + min] = temp[right++];
} else {
data[index1 + min] = temp[left++];
}
} else {
data[index1 + min] = temp[right++];
}
} else {
data[index1 + min] = temp[left++];
}
}
return comp;
}
}