我一直在尝试实现我的“自己的”MergeSort,它似乎适用于较小的值,但我正在以随机顺序在 1-100,000 的数组上尝试它,并在我打印回来时混合了一些奇怪的数字。我已经跟踪了 10 次,但没有运气。
public static void mergeSort(int[] array){
if(array.length > 1){
int midPoint = array.length/2;
int[] leftArray = new int[midPoint];
int[] rightArray = new int[array.length - midPoint];
System.arraycopy(array, 0, leftArray, 0, midPoint);
System.arraycopy(array, midPoint, rightArray, 0, array.length - midPoint);
mergeSort(leftArray);
mergeSort(rightArray);
merge(leftArray, rightArray, array);
}
}
public static void merge(int[] left, int[] right, int[] bigArray){
int counterLeft = 0, counterRight = 0, counterNewArray = 0;
while(counterLeft < left.length && counterRight < right.length){
if(left[counterLeft] < right[counterRight]){
bigArray[counterNewArray] = left[counterLeft];
counterLeft++;
counterNewArray++;
}else{
bigArray[counterNewArray] = right[counterRight];
counterRight++;
counterNewArray++;
}
}
while(counterLeft < left.length){
bigArray[counterNewArray] = left[counterLeft];
counterLeft++;
}
while(counterRight < right.length){
bigArray[counterNewArray] = right[counterRight];
counterRight++;
}
if(bigArray.length < 500){
System.out.println("Merged array:");
for(int i = 0; i < bigArray.length; i++){
System.out.println(bigArray[i]);
}
}
}