gpt4 book ai didi

java - 在我的合并排序中出现堆栈溢出错误

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

我在合并排序中遇到堆栈溢出错误。还不确定为什么。

//BAD CODE BAD CODE
public static void main(String[] args) {
int[] S = {3,4,6,2,5,3,7};
mergesort(S, 1, 5);
System.out.println(S);
}

public static void mergesort(int[] S, int left, int right){
if (right <= 1) { return; }
int mid = (right + left) / 2;
mergesort (S, left, mid);
mergesort (S, mid+1, right);
merge(S, left, mid, right);
}

public static void merge(int[] S, int left, int mid, int right){
int i, j;
int[] aux = new int[S.length];

for (i = mid+1; i > left; i--) {aux[i-1] = S[i-1];}
for (j = mid; j < right; j++) {aux[right+mid-j] = S[j+1];}
for (int k = left; k <= right; k++){
if (aux[j] < aux[i]) {
S[k] = aux[j--];
} else{
S[k] = aux[i++];
}
}
}
//END OF BAD CODE

更新

感谢您的所有快速回复,我让它正常工作并提出了一些建议的更改。复制粘贴,试一试:

//GOOD CODE
package longest_sequence_proj;
import java.util.*;

public class MergeTest {

/**
* @param args
*/
public static void main(String[] args) {
int[] S = {3,4,6,2,5,3,7};

mergesort(S, 0, 6);

System.out.println(Arrays.toString(S));

}



public static void mergesort(int[] S, int left, int right){
if (right <= left) { return; }
int mid = (right + left) / 2;
mergesort (S, left, mid);
mergesort (S, mid+1, right);
merge(S, left, mid, right);

}

public static void merge(int[] S, int left, int mid, int right){
int i, j;
int[] aux = new int[S.length];

for (i = mid+1; i > left; i--) {aux[i-1] = S[i-1];}
for (j = mid; j < right; j++) {aux[right+mid-j] = S[j+1];}
for (int k = left; k <= right; k++){
if (aux[j] < aux[i]) {
S[k] = aux[j--];
} else{
S[k] = aux[i++];
}
}
}
}

最佳答案

你的停止条款是错误的:

 if (right <= 1) { return; }

您实际上想在使用的部分数组的大小 小于 1 时停止,因此您可能正在寻找:

if (right - left <= 1) { return; }

作为旁注:

System.out.println(S);

我猜这不是你想要的(它不打印数组,而是对象的标识符...)
为了打印数组使用:

System.out.println(Arrays.toString(S));

关于java - 在我的合并排序中出现堆栈溢出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12656587/

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