gpt4 book ai didi

java - 几个小时后无法让我的归并排序工作

转载 作者:行者123 更新时间:2023-12-01 13:17:11 25 4
gpt4 key购买 nike

*嘿。所以我的合并排序遇到了问题。我尝试过不同的途径和方法,但无法使其发挥作用。我了解合并排序的原理,所以没问题。这是我的方法:

public static void TopDownMergeSort(int[] left, int[] right, int n){
TopDownSplitMerge(left, 0, n, right);
}

public static void CopyArray(int[] right, int start, int end, int[] left){
for (int i = start;i < end; i++){
right[i] = left[i];
}
}

public static void TopDownSplitMerge(int[] left, int start, int end, int[] right){
if (end - start < 2){
int middle = (end + start)/2;
TopDownSplitMerge(left, start, middle, right);
TopDownSplitMerge(left, middle, end, right);
TopDownMerge(left, start, middle, end, right);
CopyArray(right, start, end, left);
}
}

public static void TopDownMerge(int[]left, int start, int middle, int end, int[]right){

int i1 = start, i2 = middle;

for (int i = start; i < end; i++){
if (i1 < middle && (i2 >= end || left[i1] <= left[i2])){
right[i] = left[i1++];
}
else {
right[i] = left[i2++];
}
}
}

public static int[] mergeSort(int[] in) {
int[] arr = in.clone();
int[] temp = in.clone();

TopDownSplitMerge(arr,0,arr.length,temp);
return arr;
}

这就是我测试 mergeSort 的方式。

int[] list = {2,5,8,6,9,7,3,4};

System.out.println("Before mergesort: "+Arrays.toString(list));

int[] ne = SortingAlgorithms.mergeSort(list);

System.out.println("After mergesort: "+Arrays.toString(ne));

最佳答案

if (end - start < 2)

是错误的。应该是

if (end - start > 2)

关于java - 几个小时后无法让我的归并排序工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22374743/

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