73.6k views
5 votes
Consider a company that needs to sort an array of structures of type Customer by balance, with the largest balance first. Here is the definition of the Customer structure: struct Customer { string name ; double balance ; } In real life the Customer array may have thousands of data members and occupy a large area of memory, making it computationally expensive to move Customer objects around while sorting . In this problem, you will create an array of only 10 structures, say Customer data[10]. You also can define an auxiliary array Customer *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 Customer objects in decreasing order by balance, meaning that pdata[0] now points to the customer with the highest balance, and pData[9] points to the customer with the smallest balance.

User Rottitime
by
5.1k points

1 Answer

4 votes

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;

}

}

Step-by-step explanation:

The line #include <iostream> initializes the program.

This program created an array of only 10 structures, Customer data. Also defined an auxiliary array Customer *pData.

The program uses these parameters to sorts the array of pointers so that when you go through pData in increasing order of index k, the entries pData[k] point to Customer objects in decreasing order by balance, meaning that pdata[0] now points to the customer with the highest balance, and pData[9] points to the customer with the smallest balance.

User Greg Olmstead
by
4.8k points