Exercise · Algorithms and Complexity · lesson 8 of 9
Exercise: sort by key
Write a function void sort_by_age(std::vector<Person>& people) that orders people by age, youngest first. People of the same age must stay in the order they had before the call. The file already defines the Person struct, a group of named fields: p.name is the name and p.age is the age.
{{"a", 30}, {"b", 25}, {"c", 40}}→{{"b", 25}, {"a", 30}, {"c", 40}}{{"a", 30}, {"b", 20}, {"c", 30}, {"d", 20}}→{{"b", 20}, {"d", 20}, {"a", 30}, {"c", 30}}
Constraints: the vector may be empty, and different people may have the same age. The checks include a vector of 26 people named A, B, …, Z with ages 2, 1, 2, 1, …: after sorting, all the people aged 1 come first, then all those aged 2, and each group keeps its order.
Do not add extra #include lines unless the task says so explicitly.
Subscribe to take the course
The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.