I was implementing this merge sort procedure but it's throwing out of bounds exception and i can't figure why it's doing so I checked all the array parameters are satisfied but its still having the problem.
public class MergeSort
{
public static void main(String[] args) throws ArrayIndexOutOfBoundsException
{
int a[]={2,4,5,7,1,2,3,6};
System.out.println("Unsorted Array");
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
try{
MergeSort m=new MergeSort();
a=m.merge(a, 0, 3, 7);
}
catch(Exception e )
{
e.printStackTrace();
}
System.out.println("\nSorted Array");
for(int i=0;i<a.length;i++)
{
System.out.print(a[i]+" ");
}
}
int [] merge(int a[],int p,int q,int r)
{
//int a[]={2,4,5,7,1,2,3,6};
int n1=r-p+1;
int n2=r-q;
int L[]=new int[n1+1];
int R[]=new int[n2+1];
for(int i=0;i<n1;i++)
{
L[i]=a[i];
}
q=q+1;
for(int i=0;i<n2-1;i++)
{
R[i]=a[q+i];
}
//L[n1+1]=9;
///R[n2+1]=9;
int i=0,j=0;
for(int k=0;k<r;k++)
{
if(L[i]<=R[j])
{
a[k]=L[i];
i++;
}
else
{
a[k]=R[j];
j++;
}
}
return a;
}
}
Unsorted Array
2 4 5 7 1 2 3 6 java.lang.ArrayIndexOutOfBoundsException: 5
at scom.id.MergeSort.merge(MergeSort.java:63)
at scom.id.MergeSort.main(MergeSort.java:20)
Sorted Array
1 2 2 3 0 0 3 6
{on separate lines. That is a perfectly valid code style. Undo'ing edit.