#include <stdio.h>
void mergesort();
void merge();
int main()
{
int a[40], n;
printf("\nEnter the number of elements:");
scanf("%d", &n);
printf("\nEnter the %d elements:", n);
for (int i = 0; i < n; i )
{
scanf("%d", &a[i]);
}
mergesort(a, 0, n - 1);
printf("\nThe Sorted array is: ");
for (int i = 0; i < n; i )
{
printf("%d ", a[i]);
}
return 0;
}
void mergesort(int a[], int first, int last)
{
int mid;
if (first < last)
{
mid = (mid last) / 2;
mergesort(a, first, mid);
mergesort(a, mid 1, last);
merge(a, first, mid, last);
}
}
void merge(int a[], int first, int mid, int last)
{
int b[50];
int i, j, k;
i = first;
j = mid 1;
k = first;
while (i <= mid && j <= last)
{
if (a[i] <= a[j])
b[k ] = a[i ];
else
b[k ] = a[j ];
}
if (i > mid)
{
while (j <= last)
b[k ] = a[j ];
}
else
{
while (i <= mid)
b[k ] = a[i ];
}
for (i = first; i <= last; i )
a[i] = b[i];
}
I have written this Merge Sort program in C. It shows "Segmentation fault (core dumped)" after implementation of arrays. I don't know what is the issue. So please help me out i have exam on the next day. I get output like this
Enter the number of elements:5
Enter the 5 elements:1 2 3 5 4 Segmentation fault (core dumped)
It was found that I made a mistake while implementing mid variable. The correct one is:
mid=(first last)/2;
Thank you all for your helps. Each and every of your replies were useful in identifying the error.
CodePudding user response:
The program has undefined behavior since you read mid
when it's uninitialized:
void mergesort(int a[], int first, int last) {
int mid;
if (first < last) {
mid = (mid last) / 2;
// ^^^
You probably want:
mid = (first last) / 2;
CodePudding user response:
void mergesort(int a[],int first,int last)
{
int mid;
if(first<last)
{
mid=(mid last)/2;
mergesort(a,first,mid);
mergesort(a,mid 1,last);
merge(a,first,mid,last);
}
}
When this runs the first time, mid
is not guaranteed to be 0 or any other number; mid is some integer that may change every time. Thus, the number you are getting may be well outside the bounds of the array. Initializing mid to 0 would fix that, but as the answers above me point out you actually want to do mid = (first last) / 2