Slip27_1 : Read the data from the file and sort on names in alphabetical order (use strcmp) using Merge sort and write the sorted data to another file 'sortedemponname.txt'

 Solution :

#include<stdio.h>

#include<stdlib.h>

#include<string.h>

struct employee

{

 char name[20];

 int age;

}emp[10];

int readFile(struct employee a[])

{

 int i=0;

 FILE *fp;

 if((fp=fopen("emp.txt","r"))!=NULL)

 {

 while(!feof(fp))

 {

 fscanf(fp,"%s%d",&a[i].name,&a[i].age);

 i++;

 }

 }

 return i-1;

}

mergesort(struct employee a[10],int lb,int ub)

{ int mid;

 if(lb<ub)

 {

 mid=(lb+ub)/2;

 mergesort(a,lb,mid);

 mergesort(a,mid+1,ub);

 merge(a,lb,mid,ub);

 }

}

merge(struct employee a[10],int lb,int mid,int ub)

{

 struct employee b[20];

 int k,i,j;

 k=0;

 i=lb;

 j=mid+1;

 while(i<=mid && j<=ub)

 {

 //if(a[i]<=a[j])

 if(strcmp(a[i].name,a[j].name)<0)

 { b[k]=a[i];

 i++;

 k++;

 }

 else

 { b[k]=a[j];

 j++;

 k++;

 }

 }

 while(i<=mid)

 {

 b[k]=a[i];

 i++;

 k++;

 }

 while(j<=ub)

{

 b[k]=a[j];

 j++;

 k++;

 }

 for(i=lb,k=0;i<=ub;k++,i++)

 {

 a[i]=b[k];

 }

}

void writeFile(struct employee a[],int n)

{

 int i=0;

 FILE *fp;

 if((fp=fopen("sortedemp_merge.txt","w"))!=NULL)

 {

 for(i=0;i<n;i++)

 { fprintf(fp,"%s %d\n",a[i].name,a[i].age);

 }

 }

}

main()

{ int n;

 n=readFile(emp);

 if(n==-1)

 printf("File not found ");

 else

 {

 mergesort(emp,0,n-1);

 writeFile(emp,n);

 printf("File Sorted ");

 }

}


Comments

Popular posts from this blog

Slip 22_2: Read the data from file 'cities.txt' containing names of cities and their STD codes. Accept a name of the city from user and use sentinel linear search algorithm to check whether the name is present in the file and output the STD code, otherwise output “city not in the list”. Solution :

Slip10_2, 30_1 : Read the data from the file “employee.txt” and sort on names in alphabetical order (use strcmp) using bubble sort or selection sort

Slip 10_1 ,22_1: Implement a linear queue library (st_queue.h) of integers using a static implementation of the queue and implementing the init(Q), add(Q) and peek(Q) operations. Write a program that includes queue library and calls different queue operations