In case you are using a class or structure to store the firstName & lastName,
you can use the following code to
#include
#include
class Name
{
public:
char firstName[20];
char lastName[20];
public:
Name(char first[20], char last[20])
{
strcpy(firstName,first);
strcpy(lastName,last);
}
Name(Name &name)
{
strcpy(firstName,name.firstName);
strcpy(lastName,name.lastName);
}
Name &operator=(Name &name)
{
strcpy(firstName,name.firstName);
strcpy(lastName,name.lastName);
return *this;
}
};
void sortByLastName(Name nameList[100], int count)
{
int index1, index2;
for(index1=0; index1
{
for(index2=index1+1; index2
{
if(strcmp(nameList[index1].lastName, nameList[index2].lastName)>0)
{
Name tempName = nameList[index1];
nameList[index1] = nameList[index2];
nameList[index2] = tempName;
}
}
}
}
void display(Name nameList[100], int count)
{
int index;
for(index=0; index
{
cout << nameList[index].lastName << " " << nameList[index].firstName << endl;
}
}
In case you are using two arrays, containing the firstName & lastName,
you have to sort both the arrays together based on the lastName.
#include
#include
void sortByLastName(char firstName[][20], char lastName[][20], int count)
{
int index1, index2;
for(index1=0; index1
{
for(index2=index1+1; index2
{
if(strcmp(lastName[index1], lastName[index2])>0)
{
char tempName[20];
strcpy(tempName,lastName[index1]);
strcpy(lastName[index1],lastName[index2]);
strcpy(lastName[index2],tempName);
strcpy(tempName,firstName[index1]);
strcpy(firstName[index1],firstName[index2]);
strcpy(firstName[index2],tempName);
}
}
}
}
void display(char firstName[][20], char lastName[][20], int count)
{
int index;
for(index=0; index
{
cout << lastName[index] << " " << firstName[index] << endl;
}
}
2006-09-11 20:07:06
·
answer #1
·
answered by mashiur1973 2
·
0⤊
0⤋
There is not enough information to give you any kind of answer. But the general answer is to just use a bubble sort. Do a search on it and you should find one pretty quick.
2006-09-11 01:05:22
·
answer #2
·
answered by soulblazer28 2
·
0⤊
0⤋