日期:2014-05-20  浏览次数:20807 次

归并排序的问题,数组越界
归并排序

源码如下:

  

package AllKindsOfSort;

public class MergingSort {
 void Merge(int[] sourceArr,int[] toArr,int i,int m,int n)
{
//i为数组sourceArr的起始,m为归并的分界,一般设为sourceArr.length/2,n为末位置
int j,k;
for(j=m+1,k=i;j<=n&&i<=m;++k)
{
if(sourceArr[i]<=sourceArr[j])toArr[k]=sourceArr[i++];//归并,把大的放到目的数组中
else toArr[k]=sourceArr[j++];
}
if(j<=n)while(j<=n&&k<=m){toArr[k++]=sourceArr[j++];}//剩余的直接复制到目的数组
if(i<m)while(i<m&&k<=n){toArr[k++]=sourceArr[i++];}
}
void MSort(int[] sourceArr,int[] toArr,int start,int end)
{
if(start==end)//一次递归的结束条件,就是只剩下一个元素的时候
{
toArr[start]=sourceArr[start]; //1. 总是在这里抛出错误:
//ArrayIndexOutOfBoundsException: 2
}
else
{
int m=(start+end)/2+1;//得到分界
int[] toArr1= new int[end-start+1];
MSort(sourceArr,toArr1,start,m-1);//递归调用,排序m前面的部分
MSort(sourceArr,toArr1,m,end);//m后面的部分
Merge(toArr1,toArr,start,m,end);//把两个部分和在一起
}
}
 void MergeSort(int[] sourceArr)
{
MSort(sourceArr,sourceArr,0,sourceArr.length-1);
 
}

public static void main(String[] args)
{
  int[] arr=new int[]{23,54,23,1,54,98,435,34,756123,547,87,459,561,3};
  MergingSort ms=new MergingSort();
  ms.MergeSort(arr);
  for(int arrI:arr)
  {
System.out.print(arrI+" ");
  }
}
}


程序总是在1处出现数组越界的错误,我查了还几遍,还是老样子,忘各路高手解答!




------解决方案--------------------
public class MergeSort {
public static int[] sort(int[] number1, 
int[] number2) {
int[] number3 = 
new int[number1.length + number2.length];

int i = 0, j = 0, k = 0; 

while(i < number1.length && j < number2.length) { 
if(number1[i] <= number2[j]) 
number3[k++] = number1[i++]; 
else 
number3[k++] = number2[j++]; 


while(i < number1.length) 
number3[k++] = number1[i++]; 
while(j < number2.length) 
number3[k++] = number2[j++];

return number3;
}
}
------解决方案--------------------
debug this program,the step before Exception occured there has:
toArr:[0] [1]
start:2
end:2

toArr[start] throw the ArrayIndexOutOfBoundsException.