通过合并排序算法排序

时间:2017-03-01 05:50:30

标签: sorting

这是合并排序程序。我追踪这个程序,发现在对数组的前四个元素进行排序之后,再次执行对带有元素4,6的左数组的sort函数的递归调用,将'k'递增到上限并抛出ArrayIndexOutofBound索引。我无法弄清楚完整的流程。请帮忙。

    class MergeSort
{
static int k=0;
static int a[]={2,1,4,6,8,5,3,9};

public static void main(String args[])
{

int i;
System.out.println("Before");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
System.out.println("\n");

sort(a);

System.out.println("\nAfter");
for(i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
System.out.println("\n");
}

public static void sort(int b[])
{

int n=b.length;

if(n<2)
return;

int mid=n/2;
int left[]=new int[mid];
int right[]=new int[n-mid];
int i;

System.out.print("left ");
for(i=0;i<mid;i++)
{
left[i]=b[i];
System.out.print(left[i]+" ");
}
System.out.println();
System.out.print("right ");
for(i=mid;i<n;i++)
{
right[i-mid]=b[i];
System.out.print(right[i-mid]+" ");
}
System.out.println("\n");

sort(left);
sort(right);
merge(left,right);
}

public static void merge(int l[], int r[])
{

int i=0;
int j=0;

while(i<l.length && j<r.length)
{

if(l[i] < r[j]){
a[k]=l[i];
System.out.println("a["+k+"]="+a[k]);
i++;
}
else
{
a[k]=r[j];
System.out.println("a["+k+"]="+a[k]);
j++;
}
k++;
}
while(i<l.length)
{
a[k]=l[i];
System.out.println("a["+k+"]="+a[k]);
i++;
k++;
}
while(j<r.length)
{
a[k]=r[j];
System.out.println("a["+k+"]="+a[k]);
j++;
k++;

}
}

}

0 个答案:

没有答案