Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

in c++ Consider a company that needs to sort an array Person data[10] of structu

ID: 3779725 • Letter: I

Question

in c++ Consider a company that needs to sort an array Person data[10] of structures of type Person by name.

struct Person

{

string name;

int age;

}

In real life the Person structures may have many members and occupy a large area of memory, making it computationally expensive to move Person objects around while sorting. You can define an auxiliary array Person *pData[10], setting each entry of pData[k] to point to the corresponding entry of data[k]. Write a program that sorts the array of pointers so that when you go through pData in increasing order of index k, the entries pData[k] point to Person objects in ascending alphabetic order of names.

Explanation / Answer

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
struct Person
{
   string name;
   int age;
};
int main()
{
struct Person data[10];
struct Person *pData[10],*temp;
string names[] = {"a","b","c","g","z","l","p","q","r","w"};
int num[] = {4,6,34,8,13,90,33,22,18,23};
for(int i=0;i<9;i++)
{
    data[i].name = names[i];
    data[i].age = num[i];
    pData[i] = &data[i];
}
for(int i=0;i<9;i++)
{
    for(int j=i+1;j<9;j++)
    {
        if(pData[i]->name.compare(pData[j]->name)>0)
        {
            temp = pData[i];
            pData[i] = pData[j];
            pData[j] = temp;
        }
    }
}
for(int i=0;i<9;i++)
{
    cout<<pData[i]->name<<" "<<pData[i]->age<<endl;
}
}