Trying to fix this merge sort code

Hey all
Ive written this merge sort code that uses an array of structures that sorts the data according to the name of the student.Im getting a seg fault here..Pls help!

#include<stdio.h>

#include<stdlib.h>

#include<time.h>

#include<string.h>
typedef struct record
{
char regno[11];
char name[21];
float cgpa;
}record;
void merge_sort(record[], int, int);
void merge(record[], int, int, int);
//int name_is_less_than_or_equal_to(record *a,record *b);
double time_elapsed(struct timespec start ,struct timespec end);

int main()

{
int n;
record list[3];
int i=0;
int low=0;
int high=3;
struct timespec start,end;
scanf("%d",&n);
clock_gettime(CLOCK_REALTIME,&start);
while(n--)
{
for(i = 0; i < 3; i++)
{
fscanf(stdin, "%s %s %f", list[i].regno, list[i].name, &list[i].cgpa);
}
merge_sort(list, low, high);
for(i = 0; i < 3; i++)
{
fprintf(stdout, "%s %s\n %f\n", list[i].regno, list[i].name, list[i].cgpa);
}

}
clock_gettime(CLOCK_REALTIME,&end);

printf("Execution time is : %.31f microsec.\n",time_elapsed(start,end));
return 0;

}
double time_elapsed(struct timespec start,struct timespec end)

{

double t;

t=(end.tv_sec-start.tv_sec)*1000000;

t+=(end.tv_nsec-start.tv_nsec)*0.001;

return t;

}
void merge_sort(record a[], int low, int high)
{
if(low<high)
{
int m=(low+high)/2;
merge_sort(a,low,high);
merge_sort(a,m+1,high);
merge(a,low,m,high);
}
}
void merge(record a[],int low,int mid,int high)
{
record c[100];
int i=low;
int j=mid;
int k=low;
while(i<=mid && j<=high)
{
int x=strcmp(a[i].name,a[j].name);
if(x<=0)
c[k++]=a[i++];
else
c[k++]=a[j++];
}
if(j>high)
{
while(i<=mid)
c[k++]=a[i++];
}
else
{
while(j<=high)
c[k++]=a[j++];
}
for(i=0;i<=high;i++)
a[i]=c[i];
}
Ive written this merge sort code that uses an array of structures that sorts the data according to the name of the student.Im getting a seg fault here..Pls help!

Welcome to this forum. Please take time and read the "Before posting" tutorial And also edit your thread and use code tags to make your code readable - http://www.cplusplus.com/articles/jEywvCM9/

You also forgot to ask a question. With what do you need help, are you having errors? if yes present the full error codes. Is an output not what it should be? Then what should it be, and what is it currently? Be specific, we cant read minds here.
Last edited on
Im getting a seg fault here

Most likely you have an array subscript out of range somewhere.

$ gdb a.out
> run
(input)
Program received signal SIGSEGV, Segmentation fault.
> backtrace


1
2
3
4
5
6
7
8
9
10
void merge_sort (record a[], int low, int high)
{
	if (low < high)
	{
		int m = (low + high) / 2;
		merge_sort (a, low, high); //stack overflow, you did not change the parameters.
		merge_sort (a, m + 1, high);
		merge (a, low, m, high);
	}
}
Last edited on
Topic archived. No new replies allowed.