Practice
Sort Names by Surname
2026/Feb/Mar·Variant 2·Q5·[8 marks]
MEDIUM2D Arrays
Four people are stored in a 2D array Names[1:4, 1:2]: column 1 is the last name, column 2 is the first name. Read the four pairs (last name then first name), bubble-sort the rows into ascending last-name order, and output each person as Last First.
Equal last names should keep their original order.
Input: Eight strings — last name, first name, four times. Output: Four lines after sorting.
Example:
Input: Chen
Amy
Patel
Bo
Adams
Cy
Chen
Dan
Output: Adams Cy
Chen Amy
Chen Dan
Patel Bo
Sample Test Cases
Test 1: Two Chens keep input order
Inputs: Chen, Amy, Patel, Bo, Adams, Cy, Chen, Dan
Expected: Adams Cy
Chen Amy
Chen Dan
Patel Bo
Test 2: Reverse alphabetical last names
Inputs: Zed, A, Yap, B, Xu, C, Wu, D
Expected: Wu D
Xu C
Yap B
Zed A