/*
This code is Written by Shankhadeep Dey
(15th Aug 2018)
*/
#include<iostream>
using namespace std;
void merge(int a[],int p,int q,int r)
{
int n1,n2,j,i,k;
n1= q-p+1;
n2= r-q;
int L[n1],R[n2];
for (i = 0; i < n1-1; ++i)
L[i]=a[p+i-1];
for (j = 0; j < n2-1; ++j)
R[j]=a[q+j];
L[n1]=1e9;
R[n2]=1e9;
i=0;
j=0;
for (k = p; k < r; ++k)
{
if (L[i]<=R[j])
{
a[k]=L[i];
i++;
}
else
{
a[k]=R[j];
j++;
}
}
while (i < n1)
{
a[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
a[k] = R[j];
j++;
k++;
}
}
void mergeSort(int a[],int p,int r)
{
int q;
if (p<r)
{
q= (p+r)/2;
mergeSort(a,p,q);
mergeSort(a,q+1,r);
merge(a,p,q,r);
}
}
int main()
{ int w[4]={4,3,21,5};
mergeSort(w,0,3);
for (int i = 0; i < 4; ++i)
{
cout<<w[i]<<" ";
}
cout<<endl;
}
Can anyone tell me why this sorting is not working?
I tried this algorithm from the book "Introduction to Algorithm" but I am not so sure why this code is not running. I tried searching online for merge sort and find so much things but I exactly want to know what is wrong with my code.
Output is:-0 1000000000 1 1000000000 (which is not the correct ans).
This is the warning I'm getting
mergeSort.cpp: In function ‘void merge(int*, int, int, int)’:
mergeSort.cpp:12:10: warning: ISO C++ forbids variable length array ‘L’ [-Wvla]
int L[n1],R[n2];
^
mergeSort.cpp:12:16: warning: ISO C++ forbids variable length array ‘R’ [-Wvla]
int L[n1],R[n2];