2017-08-29 70 views
1

練習mergeSort時遇到問題。我在線程「main」中接收異常java.lang.ArrayIndexOutOfBoundsException:1 mergeSort部分工作得很好,但重組數組對我來說很困難。任何援助將不勝感激。mergeSort ArrayIndexOutOfBoundsExecption

public class MyMergeSort { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 
     int[] arry1 = {42, 12, 30, 77, 590, 1}; 
     int[] arry2 = mergeSort(arry1); 
     System.out.println("Merge Sort Demo: "); 
     for(int i:arry2){ 
      System.out.print(i); 
      System.out.print(" "); 
     } 
     } 

     static int[] mergeSort(int[] arry1) { 

     int n = arry1.length; 
     if(n < 2) 
      return arry1; 

     int mid = n/2; 
     int left[] = new int[mid]; 
     int right[] = new int [n - mid]; 
     for(int i = 0; i< mid; i++) { 
      left[i] = arry1[i]; 
     } 
     for(int i = mid; i < n; i++) { 
      right[i - mid] = arry1[i]; 
     } 
     mergeSort(left); 
     mergeSort(right); 
     merge(arry1, left, right); 
     return(arry1); 
     } 

     public static void merge(int[] arry1, int left[], int right[]){ 
     int nL = left.length; 
     int nR = right.length; 
     int i = 0, j = 0, k= 0; 

     while(i < nL && j < nR) { 
      if(left[i] < right[j]){ 
      arry1[k] = left[i]; 
      i++; 
      } else { 
      arry1[k] = right[i]; 
      j++; 
      } 
      k++; 
     } 
     while(i < nL) { 
      arry1[k] = left[i]; 
      i++; 
      k++; 
     } 
     while(j < nR){ 
      arry1[k] = right[i]; 
      j++; 
      k++; 
     } 
    } 
} 

回答

2

在您的合併方法應該是這樣arry1 [K] =右[J];

public static void merge(int[] arry1, int left[], int right[]){ 
    int nL = left.length; 
    int nR = right.length; 
    int i = 0, j = 0, k= 0; 

    while(i < nL && j < nR) { 
     if(left[i] < right[j]){ 
     arry1[k] = left[i]; 
     i++; 
     } else { 
     **arry1[k] = right[i];** // Why i it should be j 
     j++; 
     } 
     k++; 
    } 
    while(i < nL) { 
     arry1[k] = left[i]; 
     i++; 
     k++; 
    } 
    while(j < nR){ 
     **arry1[k] = right[i];** // Why i it should be j 
     j++; 
     k++; 
    } 
} 

我相信j是對正確的,你都在增加j和只在它具有的條件,但訪問的第i個指數權,而不是第j個指標。希望能幫助到你!

+0

非常感謝!我很高興這個問題是如此簡單 – 7kevin

+0

你可以upvote並接受答案:P –

+0

哈哈對不起。它在eclipse上完美工作,但Python教師的java部分表示需要很長時間。我也在那裏運行代碼,所以我可以一步步觀察執行情況。有什麼建議麼? – 7kevin