java - MergeSort - ArrayIndexOutOfBoundsException -


i sorry if has been answered somewhere, have spent on hour searching through many previous questions , none of them able me error.

i randomly receive error, 70% of time:

--------------------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  @ mergesort.merge(mergesort.java:64) @ mergesort.mergesort(mergesort.java:26) @ driver.main(driver.java:18)  process completed. 

line 64 refer to: "scratch[scratch_index] = list[i];"

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++) // line 64     {         scratch[scratch_index] = list[i];         scratch_index +=1;     }     for(int i=0;i<list.length;i++)     {         list[i] = scratch[i];     } } 

this first question ever on site, sorry if have not formatted question correctly, advice appreciated.

if other information needed me solving error, let me know. thank you!

at comment // line 64 incrementing i , not right_index cause index keep increasing until reaching index out of bound, replace this,

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

by this:

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

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -