Parallel Array Sorting HELP Beginner here

HELP! it seems my output only compare 2 element. Any1 can help me fix and tell me the problems much appreciated.

Write a program to read 5 person's name and age from the keyboard and save them into memory using arrays. Display the list starting with the youngest person to the oldest. Assume all names are single words. Name are to be left justified while age are right justified.

A sample output of the program :

Enter 5 names:
Enter name and age for person 1 : Kim 23
Enter name and age for person 2 : Jason 18
Enter name and age for person 3 : Lee 14
Enter name and age for person 4 : Dan 34
Enter name and age for person 5 : May 8

The sorted list is :
Name Age
May 8
Lee 14
Jason 18
Dan 34
Press any key to continue......

#include <iostream>
#include <iomanip>
#include <cmath>
#include <string>
using namespace std;

int main()
{
int const limit=5;
string name[limit];
int ages[limit];
int index[limit];
int i,j;

cout<<"Enter 5 names: "<<endl;
for(i=0; i<=4; i++)
{

cout<<"Enter name and age for person "<<i+1<< " : ";
cin>>name[i]>>ages[i];
}
for(i=0;i<=4;i++)
{
index[i]=i;
}
for(i=0;i<=3;i++)
{
for(j=i+1;j<=4;j++)
{
int temp;

if(name[index[i]] < name[index[j]])
{
temp=index[i];
index[i]=index[j];
index[j]=temp;
}
}
}
cout<<endl;
cout<<"The sorted list is :"<<endl;
cout<<left<<setw(10)<<"Name"<<left<<setw(10)<<"Age"<<endl;

for(i=0;i<=4;i++)
{
cout<<left<<setw(10)<<name[index[i]]<<left<<setw(10)<<ages[index[i]]<<endl;
}
system("Pause");
return 0;
}
Last edited on
You have to use parallel arrays.

Declare two arrays, both of size 5. Store names in one array and ages in the other.

Use bubble sort to sort the names array, and every time you swap element in the names array, swap the same indices in the ages array.
Last edited on
Okay. Thank you. I will try it out :)
Topic archived. No new replies allowed.