Problem Statement
In this problem we have given a text document employee.txt in which employee names and their ages are stored, such as this data:
abc 45 xyz 23 pqr 23 xuv 25 tcs 76
And we have to sort this on string i.e. on names using merge sort and store them into new text document called sorted_name_employee.txt.
I have tried something but this is not giving an appropriate output.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct employee
{
char name[10];
int age;
} emp[20];
void m_sort(struct employee *a, int low, int up);
void merge(struct employee *a, struct employee *temp, int low1, int up1, int low2, int up2);
int total_records(struct employee *a);
void copy(struct employee *a, struct employee *temp, int low, int up);
void write_into_file(struct employee *a, int n);
int main()
{
int i = 0, n;
struct employee emp[20];
n = total_records(emp);
//printf("n in main:- %d\n", n);
m_sort(emp, 0, n - 1);
/*for (i = 0; i <= n; i++)
{
printf("%s %d\n", emp[i].name, emp[i].age);
}*/
write_into_file(emp, n);
printf("Data has been written into 'sorted_name_emp.txt'");
}
int total_records(struct employee *a)
{
int i = 0;
FILE *fp;
fp = fopen("employee.txt", "r");
if (fp == NULL)
{
printf("Error!");
exit(1);
}
else
{
while (!feof(fp))
{
fscanf(fp, "%s %d", a[i].name, &a[i].age);
i++;
}
}
return (i - 1);
}
void m_sort(struct employee *a, int low, int up)
{
int mid;
struct employee temp_emp[20];
if (low < up)
{
mid = (low + up) / 2;
m_sort(a, low, mid);
m_sort(a, mid + 1, up);
merge(a, temp_emp, low, mid, mid + 1, up);
copy(a, temp_emp, low, up);
}
}
void merge(struct employee *a, struct employee *temp, int low1, int up1, int low2, int up2)
{
int i = low1, j = low2, k = low1;
while ((i <= up1) && (j <= up2))
{
if (strcmp(a[i].name, a[j].name) <= 0)
{
strcpy(temp[k].name, a[i].name);
temp[k].age = a[i].age;
k++;
i++;
}
else
{
strcpy(temp[k].name, a[j].name);
temp[k].age = a[j].age;
k++;
j++;
}
}
while (i <= up1)
{
strcpy(temp[k].name, a[i].name);
temp[k].age = a[i].age;
k++;
i++;
}
while (j <= up2)
{
strcpy(temp[k].name, a[j].name);
temp[k].age = a[j].age;
k++;
j++;
}
}
void copy(struct employee *a, struct employee *temp, int low, int up)
{
int i = 0;
for (i = 0; i <= up; i++)
{
strcpy(a[i].name, temp[i].name);
a[i].age = temp[i].age;
}
}
void write_into_file(struct employee *a, int n)
{
int i;
FILE *fp;
fp = fopen("sorted_name_emp.txt", "w");
if (fp == NULL)
{
printf("Error!");
exit(1);
}
for (i = 0; i <= n; i++)
{
fprintf(fp, "%s %d\n", a[i].name, a[i].age);
}
}
Actual Ouptput in sorted_name_emp.txt:
abc 45
pqr 23
xuv 25
xyz 56
tcs 76