我正在尝试在遗传类型的数组上实现Merge Sort算法。问题是结果不正确,因为有些元素被设置为0.我怀疑问题来自于我在整个程序中所做的转换,但我不确切知道原因。
正如您在sortUsingMerge()中看到的,我将一个Object数组转换为泛型。同样在下面的IF语句中,我将数组中的Object元素转换为int,以便能够比较2个元素。我的意图是排序算法应该适用于任何类型的任何数组,但我现在不想为每种类型编写Comparator。
Input array: 5 1 -2 3 7 8 0
Output: -2 0 1 1 3 7 0
在排序过程中,看起来数字5和8以某种方式转换为不同的数字。有人能告诉我为什么吗?谢谢!
Source code:
public void sortUsingMerge(){
Object[] array = (E[]) new Object[size];
Object[] helper = (E[]) new Object[size];
mergeSort(array,helper,0,size-1);
}
public void mergeSort(Object[] array, Object[] helper, int low, int high){
if (low<high){
int mid = (low + high)/2;
mergeSort(array,helper,low,mid); //sort left half
mergeSort(array,helper,mid+1,high);//sort right half
merge(array,helper,low,mid,high);
}
}
public void merge(Object[] array, Object[] helper, int low, int mid, int high){
for (int i=low; i<=high; i++){// copy both parts into helper array
helper[i] = array[i];
}
int helperLeft = low;
int helperRight = mid + 1;
int current = low;
while (helperLeft <= mid && helperRight <=high){
if ((int)helper[helperLeft] <= (int)helper[helperRight]){
array[current] = helper[helperLeft];
helperLeft++;
}
else{
array[current] = helper[helperRight];
helperRight++;
}
current++;
}
int remain = mid - helperLeft;
for (int i=0; i<remain; i++){
array[current+i] = helper[helperLeft + i];
}
}
答案 0 :(得分:4)
内部合并替换
for (int i=0; i<remain; i++){
array[current+i] = helper[helperLeft + i];
}
带
while (helperLeft <= mid) {
array[current] = helper[helperLeft];
current++;
helperLeft++;
}
答案 1 :(得分:1)
施放不会给你那种错误。您在合并结束时遇到错误。
int remain = mid - helperLeft;
for (int i=0; i <= remain; i++) { //changed < to <=
array[current+i] = helper[helperLeft + i];
}