SAVITIBAI PHULE UNIVERSITY OF PUNE
S. Y. B.Sc. (Computer Science) Semester III
Practical Examination
SUBJECT: CS-233 Practical course based on CS231
/* Q. 2. Read the data from the file "employee.txt" and sort on names in alphabetical order (use strcmp) using insertion sort and selection sort */
// File Name: "employee.txt" (This file create separate with txt extension and save in current folder.)
John
Aniket
Julie
Dolly
Rosemary
// File Name: "Slip21_2.c"
#include<stdio.h>
#include<stdlib.h>
#define MAX 20
typedef struct employee{
char name[MAX];
}record;
record emp[MAX];
int read_file(record *a){
int i = 0;
FILE *fp;
if ((fp = fopen("employee.txt", "r")) != NULL)
{
while (!feof(fp)){
fscanf(fp, "%s", a[i].name);
i++;
}
}
return (i-1);
}
void InsertionSort(record *a, int n)
{
int i, j;
record elem;
for (i = 1; i <= n; i++)
{
elem = a[i];
for (j = i-1; strcmp(a[j].name, elem.name) > 0 && j > 0; j--)
{
a[j + 1] = a[j];
}
a[i] = elem;
}
}
void SelectionSort(int A[], int n)
{
int i = 0, j = 0, loc = 0, min = 0, temp = 0;
for ( i = 0; i < n-1; i++)
{
min = A[i];
loc = i;
for ( j = i+1; j < n; j++)
{
if ( min > A[j])
{
min = A[j];
loc = j;
}
}
temp = A[i];
A[i] = A[loc];
A[loc] = temp;
}
}
void display(record *a, int n)
{
int i;
printf("\n\n");
for (i = 0; i < n; i++) {
printf("%s ", a[i].name);
}
printf("\n\n");
}
int main()
{
int n = read_file(emp);
printf("%d", n);
InsertionSort(emp, n);
display(emp, n);
int n = read_file(emp);
printf("%d", n);
SelectionSort(emp, n);
display(emp, n);
system("pause");
return 0;
}
No comments:
Post a Comment