DS-(I) Assignment 2: Set B-a) Bubble Sort

a) Read the data from the file “employee.txt” and sort on age using bubble sort.

Solution: 

#include<stdio.h>
typedef struct employee
{
    char name[10];
    int age;
    long int salary;
}RECORD;
RECORD employee[100];
int readfile(RECORD *a)
{
    int i=0;
    FILE *fp;
    if((fp=fopen("employee.txt","r"))!=NULL)
    {
        while(!feof(fp))
        {
       fscanf(fp,"%s%d%ld",a[i].name,&a[i].age,&a[i].salary);
            i++;
        }
    }
    return(i-1);
}
void writefile(RECORD *a,int n)
{
    int i=0;
    FILE *fp;
    if((fp=fopen("sorted_employee_age.txt","w"))!=NULL)
    {
        for(i=0;i<n;i++)
           fprintf(fp,"%s\t%d\t%ld\n",a[i].name,a[i].age,a[i].salary);
   }
}
void bubble_sort(RECORD *a,int n)
{
    int i,j;
    RECORD t;
    for(i=1;i<n;i++)
    {
        for(j=0;j<n-i;j++)
        {
            if(a[j].age>a[j+1].age)
            {
                t=a[j];
                a[j]=a[j+1];
                a[j+1]=t;
            }
        }
   }

    printf("\nSorting Done!\n");
}
main()
{
    int n;
    n=readfile(employee);
    bubble_sort(employee,n);
    writefile(employee,n);
}

0 Comments:

Post a Comment