Reputation: 5162
public static void Merge(int[] arr,int p,int q,int r )
{
int n1 = q-p;
int n2 = r-q;
int[] L=new int[n1];
int[] R = new int[r-n2];
for (int i = 0; i < n1; i++)
L[i] = arr[i];
foreach (int x in L)
Console.WriteLine(x);
for (int i = 0; i < n2; i++)
R[i] = arr[q+i];
Console.WriteLine("New part");
foreach (int x in R)
Console.WriteLine(x);
int k=0, d=0;
for (int i = p; i < r; i++)
{
if (L[k] <= R[k])
{
arr[i] = L[k];
k++;
}
else
{
arr[i] = R[d];
d++;
}
}
}
The above code shows exception(index out of bound when I call from main() method using Merge(arr,0,0,12)
. Where arr is an int array of length 12.
Upvotes: 0
Views: 92
Reputation: 170
You get an Index out of bounds exception in this part:
for (int i = 0; i < n2; i++)
R[i] = arr[q+i];
Your R-array is of size 0, while n2 is defined as 12 with the given arguments.
Upvotes: 2
Reputation: 1026
Both you L and R array are defined as too small
Initialize them like this instead:
int[] L = new int[arr.Length];
int[] R = new int[arr.Length];
Upvotes: 1