gpt4 book ai didi

java - MergeSort 不稳定

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:02:42 25 4
gpt4 key购买 nike

我一直在尝试实现我的“自己的”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]);
}
}
}

最佳答案

merge 结束时,当您添加每一边的剩余部分时...您不会递增 counterNewArray。这导致一堆值被分配到一个位置,相互覆盖......并在 bigArray 的尾部留下无效值(零,IIRC)。

关于java - MergeSort 不稳定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14658362/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com