I am trying merge sort an array of 5 numbers. g++ compiles the program without error but i am unable to execute due to segmentation fault 11. I have read the article on segmentation faults. I think writing off array endings might be responsible. How do I correct it?
Code:
#include <fstream>
#include <iostream>
using namespace std;
void sort(int A[], int size)
{
if (size==1)
return;
int left[size/2], right[size/2+1], j=0, k=0;
for(int i=1; i<=size; i++)
{
if(i<=size)
left[++j] = A[i];
else
right[++k] = A[i];
}
sort(left, j);
sort(right, k);
int a=1, l=1, r=1;
while(l+r <= j+k)
{
if((left[l]<right[r]) || (r==k))
A[a++]=left[l++];
else
A[a++]=right[r++];
}
}
int main()
{
int array[5]={4,5,1,0,10};
sort(array, 5);
for(int j=1; j<=5; j++)
cout<<array[j]<<endl;
return 1;
}