The following defines a Person type and a global array of instances: struct Pers
ID: 3771166 • Letter: T
Question
The following defines a Person type and a global array of instances:
struct Person
{
char name[40];
int age;
};
Person people[1000];
To sort an array of such items without moving the data, we create an index array and call the function Quicksort as follows:
Quicksort(people,0,999);
However, a comparison function is needed.
Write the code for the function with prototype
bool CompareData(const int&, const int&);
which takes two index values, and compares the two Person instances at those locations in the array and returns true if the first comes before the second. The order required is in increasing order of age,, however where two instances have the same age then they should be in alphabetical order by name.
You may assume the library headers for any functions needed have
been included.
this is a c++ problem.
Explanation / Answer
Assuming Persons persons[] is array and available to this function
bool CompareData(const int&x, const int&y) {
if(persons[x].age < persons[y].age)
return true;
else if(persons[x].age > persons[y].age)
return false;
else {
//if both ages are equal
return strcmp(persons[x].name, persons[y].name);
}
return false;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.