2
package merge;
public class Merger {
int[] a = {1, 10, 5, 9};
// int[] a = {1, 10, 5, 9, 8, 6, 3, 2};
public Merger(){
mergSort(a,0,3);
for(int i =0; i<a.length;i++){
//System.out.println(a[i]);
}
}
private void mergSort(int[] a, int l, int r) {
if(l>=r){
return;
}
int m=(l+r)/2;
mergSort(a,l,m);
mergSort(a,m+1,r);
merge(a,l,m,r);
}
private void merge(int[] a, int l, int m, int r) {
int p = l;
int u = l;
int v = m + 1;
int n = (r-l) + 1;
int[] result = new int[n];
int s = 0;
while(p <= r){
if(u>v){
s = a[v];
v = v + 1;
} else if (v>r){
s = a[u];
u = u + 1;
} else {
if(a[u]<a[v]){
s = a[u];
u = u + 1;
} else {
s = a[v];
v = v + 1;
}
}
result[p] = s;
p = p + 1;
}
copy(result, a, l, r);
}
private void copy(int[] result, int[] a, int l, int r) {
for(int i = l; i <= r; i++){
a[i] = result[i];
}
}
public static void main(String[] args) {
Merger m = new Merger();
}
}
我一直在線路結果拋出ArrayIndexOutOfBoundsException異常 [P] = S。我認爲這可能與最終合併有關,但我不確定。當我硬編碼結果數組的大小爲數組a的大小時,我的程序工作。我不確定發生了什麼事。我很感激任何幫助歸併數組索引越界異常