Sorting on multiple keys

Sorting on multiple keys

The sorting algorithm may be applied on multiple keys such that if first field contains duplicate values, then sorting is done on a secondary field and so on. However, if the first field contains unique values, then sorting is not applied on secondary field.  Say for example:

The input for the combination {studentname, feeamt}

{ (xyz,3000), (abc,1000), (xyz, 1000), (abc,3000)}; will result in the following output:

{ (abc,1000), (abc,3000), (xyz,1000), (xyz,3000) }.

Program to implement sorting on student names entered by the user followed by feeamt, such that wherever name is same, sorting is applicable on feeamt field is given below:

/*Sorting on multiple keys*/

#include <stdio.h>
#include <conio.h>
#include <string.h>

#define MAX 5

struct student
{char name[25];
int feeamt;
};

void sort_multiplekeys(struct student[]);

void main()
{
struct student s[MAX];
int i;
clrscr();
for(i=0;i<MAX;i++)
{printf(“\nEnter name?”);
scanf(“%s”,s[i].name);
printf(“Enter fee amount?”);
scanf(“%d”,&s[i].feeamt);
}
sort_multiplekeys(s);
printf(“\nOutput sorted on name followed by feeamt:\n\n”);
for(i=0;i<MAX;i++)
{printf(“\nName = %s”,s[i].name);
printf(“\nFeeamt = %d”,s[i].feeamt);
}
}
void sort_multiplekeys(struct student s[])
{
int i,j;
char temp[25];
float x;
clrscr();
/*loop to arrange names in ascending order*/
for(i=0;i<MAX-1;i++)
for(j=i+1;j<MAX;j++)
{if(strcmp(s[i].name,s[j].name)>0)
{
/*swapping names*/
strcpy(temp,s[i].name);
strcpy(s[i].name,s[j].name);
strcpy(s[j].name,temp);

/*swapping feeamt*/
x=s[i].feeamt;
s[i].feeamt = s[j].feeamt;
s[j].feeamt = x;
}
}
/*loop to arrange second field-feeamt in ascending order*/
for(i=0;i<MAX-1;i++)
for(j=i+1;j<MAX;j++)
{if(strcmp(s[i].name,s[j].name)==0)
{if(s[i].feeamt>s[j].feeamt)
{
/*swapping feeamt*/
x=s[i].feeamt;
s[i].feeamt=s[j].feeamt;
s[j].feeamt=x;
}
}
}
}

 

You cannot copy content of this page.