2014-04-07 2 views
0

이미 어딘가에 답변이 있으면 죄송합니다. 이전에 많은 질문을 검색하는 데 1 시간 이상을 소비했으며 그 중 누구도이 오류로 나를 도울 수 없었습니다.MergeSort - ArrayIndexOutOfBoundsException

--------------------Configuration: MergeSort - JDK version 1.7.0_45 <Default> - <Default>- ------------------- 

Random array: 17 14 3 4 1 10 13 9 3 1 6 9 10 2 17 8 10 5 7 8 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20 

at MergeSort.merge(MergeSort.java:64) 
at MergeSort.mergeSort(MergeSort.java:26) 
at Driver.main(Driver.java:18) 

Process completed. 

라인 (64)을 참조 할 것 :

I 무작위 시간 아마 70 %의 오류가 "[I] 스크래치 [scratch_index = 목록;"

public void merge(int[] list, int first, int middle, int last) 
{ 
    int[] scratch = new int[list.length]; 

    int midpoint = (first+last)/2; 

    int left_index = first; 
    int right_index = middle + 1; 
    int scratch_index = left_index; 

    while((left_index <= midpoint) && (right_index <= last)) 
    { 
     if(list[left_index] <= list[right_index]) 
     { 
      scratch[scratch_index] = list[left_index]; 
      left_index +=1; 
     } 
     else 
     { 
      scratch[scratch_index] = list[right_index]; 
      right_index +=1; 
     } 
     scratch_index +=1; 
    } 

    for(int i=left_index;i<=midpoint;i++) 
    { 
     scratch[scratch_index] = list[i]; 
     scratch_index +=1; 
    } 
    for(int i=right_index;right_index<=last;i++) // I am line 64 
    { 
     scratch[scratch_index] = list[i]; 
     scratch_index +=1; 
    } 
    for(int i=0;i<list.length;i++) 
    { 
     list[i] = scratch[i]; 
    } 
} 

이 사이트에 대한 내 첫 번째 질문입니다.이 질문에 올바르게 서식을 지정하지 않으면 죄송합니다.

이 오류를 해결하는 데 도움이되는 다른 정보가 필요하면 알려주세요. 감사합니다.

+0

이 메서드는 어디에 호출 되었습니까? – Naili

+0

게시 한 것을 시도 했습니까? – CMPS

+0

머지 소트 : 공개 무효 머지 소트 (INT []에서, 제 마지막 지능 INT) \t { \t \t 경우 (제 <마지막) \t \t { \t \t \t INT 중간 = (제 1 + 마지막)/2; \t \t \t sort (list, first, middle); \t \t \t sort (list, middle + 1, last); \t \t \t merge (list, first, middle, last); \t \t} \t} – kbhawkman

답변

0

// I am line 64이로 i 아닌 right_index 인덱스가 경계에서 인덱스에 도달 할 때까지 계속 증가하므로이 대체하게됩니다,

for(int i=right_index;right_index<=last;i++) // I am line 64 

를 증가됩니다

for(int i=right_index; i<=last;i++) 
+1

이 고정 된 모든 것, 때때로 우리는 사물의 가장 간단한 것을 놓칩니다. 도움을 주신 모든 분들께 감사드립니다 :) – kbhawkman

0

인덱스는 "제로 번호">> 문에 대한 https://en.wikipedia.org/wiki/Zero-based_numbering

String example = ""; 
System.out.println(example.size()); //Prints out 5 
System.out.println(exmaple.indexOf("1")); //Prints out 1 

귀하의 마지막 인덱스 (권장하지 않음)

for(int i=right_index;right_index<last;i++) 

또는

for(int i=right_index;right_index<=last-1;i++) //Works, but not recommended due to conventions 
까지 체크 할 필요를 사용


주석에서 691,363,210
//index  0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 
Random array: 17 14 3 4 1 10 13 9 3 1 6 9 10 2 17 8 10 5 7 8 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 20 
+0

감사합니다. 지금은 어떤 이유로 정렬 된 배열의 끝에 항상 "0"이 추가됩니다. 두 개의 for 루프를 <대신 <대신 <대신 으로 변경했습니다. 동일한 오류가 임의로 발생했습니다. 아직 해결되지 않았기 때문에 : ( – kbhawkman