我在合并排序中遇到堆栈溢出错误。还不知道为什么。
//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++];
}
}
}
}