Hi, I am trying to write a function to alphabetically sort a list of names. Here
ID: 3621808 • Letter: H
Question
Hi, I am trying to write a function to alphabetically sort a list of names. Here is the function:void abc_order(Node people[], int size)
{
int x;
int y;
int temp;
for(x=size; x>0; x--)
{
for(y=0; y<x-1; y++)
{
if(people[y].name>people[y+1].name)
{
temp = people[y+1].name;
people[y+1].name = people[y].name;
people[y].name = temp;
}
}
}
cout << "SORTED LIST ACCORDING TO LAST NAME:" << endl << endl;
for (int i = 0; i < size; i++)
{
cout << "Name: " << people[i].name << endl;
cout << "ID: " << people[i].ID << endl;
cout << "Distance: " << people[i].distance << endl << endl;
}
}
Here is the text that I am trying to sort:
April,Joe
3120
90
Matthews,Jocob
4592
88
Garfield,Kitty
8917
79
Lake,Bill
2233
85
Johnson,Jim
5672
67
Zumistan,Kim
6750
76
Larson,Mike
6718
99
Anderson,Eva
5672
80
Thank you so much! If you need to see the rest of my code to help me just let me know! Thanks!
Explanation / Answer
Hope this helps. Let me know if you have any questions. Please rate. :) You were very close!! See the two changes in comments below. void abc_order(Node people[], int size) { int x; int y; // temp should be of type Node, since it is what you are swapping around Node temp; for(x=size; x>0; x--) { for(y=0; ypeople[y+1].name) { // You want to swap all the data, not just the name, so just swap the whole Node // Set the temp Node equal to people[y+1], then reassign that Node to people[y], // then set people[y+1] back to the temp Node, and you will swap all the data at once temp = people[y+1]; people[y+1] = people[y]; people[y] = temp; } } } coutRelated Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.