in c Consider a company that needs to sort an array Person d

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.

Solution

#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;
}
}

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

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site