Selection Sort on Objects
IB Syllabus: B2.4.3, B3.1 – Apply sorting algorithms to arrays of objects using getter methods and attribute comparison.
Table of Contents
- Key Concepts
- Worked Examples
- Quick Check
- Trace Exercise
- Spot the Error
- Predict the Output
- Practice Exercises
- Connections
Key Concepts
Why Sort Objects?
In Sorting Algorithms, you sorted arrays of int values. In real programs, you sort arrays of objects – students by grade, products by price, employees by name. The sorting logic is the same, but instead of comparing values directly, you compare attributes accessed through getter methods.
Sorting by a Numeric Attribute
To sort Student objects by grade (ascending), replace direct < comparisons with getter calls:
// Selection sort: sort students by grade (ascending)
public static void sortByGrade(Student[] arr, int count) {
for (int i = 0; i < count - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < count; j++) {
if (arr[j].getGrade() < arr[minIndex].getGrade()) {
minIndex = j;
}
}
// Swap references, not individual fields
Student temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
Key differences from sorting int[]:
- The comparison uses
arr[j].getGrade()instead ofarr[j] - The swap moves object references, not primitive values
- The temp variable is type
Student, notint
Sorting by a String Attribute
To sort alphabetically by name, use .compareTo():
// Selection sort: sort students by name (alphabetical)
public static void sortByName(Student[] arr, int count) {
for (int i = 0; i < count - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < count; j++) {
if (arr[j].getName().compareTo(arr[minIndex].getName()) < 0) {
minIndex = j;
}
}
Student temp = arr[minIndex];
arr[minIndex] = arr[i];
arr[i] = temp;
}
}
.compareTo()returns an int, not a boolean. It returns a negative number if the first string comes before the second alphabetically, zero if equal, and a positive number if after. Use< 0for ascending (A-Z) and> 0for descending (Z-A).
How .compareTo() Works
| Expression | Result | Meaning |
|---|---|---|
"Alice".compareTo("Bob") | Negative (e.g., -1) | “Alice” comes before “Bob” |
"Bob".compareTo("Alice") | Positive (e.g., 1) | “Bob” comes after “Alice” |
"Alice".compareTo("Alice") | 0 | They are equal |
For ascending order (A to Z): update minIndex when arr[j].getName().compareTo(arr[minIndex].getName()) < 0 – meaning the j-th name comes before the current minimum alphabetically.
Descending Order
To sort in descending order (highest first), flip the comparison:
// Descending: find MAXIMUM instead of minimum
if (arr[j].getGrade() > arr[maxIndex].getGrade()) {
maxIndex = j;
}
For strings descending (Z to A): use > 0 instead of < 0.
Swapping Object References
When you swap objects in an array, you swap references (pointers), not the objects themselves. The objects stay in memory – only the array slots change which object they point to.
// Before swap: arr[0] -> Alice, arr[1] -> Bob
Student temp = arr[0]; // temp -> Alice
arr[0] = arr[1]; // arr[0] -> Bob
arr[1] = temp; // arr[1] -> Alice
// After swap: arr[0] -> Bob, arr[1] -> Alice
The Alice and Bob objects are not copied or modified. Only the references in the array move.
Worked Examples
Example 1: Sort Products by Price
public class Product {
private String name;
private double price;
public Product(String name, double price) {
this.name = name;
this.price = price;
}
public String getName() { return name; }
public double getPrice() { return price; }
}
Product[] shop = new Product[4];
shop[0] = new Product("Keyboard", 79.99);
shop[1] = new Product("Mouse", 29.99);
shop[2] = new Product("Monitor", 299.99);
shop[3] = new Product("Webcam", 49.99);
// Selection sort by price (ascending)
for (int i = 0; i < shop.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < shop.length; j++) {
if (shop[j].getPrice() < shop[minIndex].getPrice()) {
minIndex = j;
}
}
Product temp = shop[minIndex];
shop[minIndex] = shop[i];
shop[i] = temp;
}
// Print sorted
for (int i = 0; i < shop.length; i++) {
System.out.println(shop[i].getName() + ": $" + shop[i].getPrice());
}
Output:
Mouse: $29.99
Webcam: $49.99
Keyboard: $79.99
Monitor: $299.99
Example 2: Sort Students by Name, Then Find Top Grade
A common exam pattern: sort first, then process the sorted array.
Student[] students = new Student[4];
students[0] = new Student("Diana", 88, "Blue");
students[1] = new Student("Alice", 95, "Red");
students[2] = new Student("Charlie", 72, "Blue");
students[3] = new Student("Bob", 91, "Red");
// Sort by name (alphabetical)
for (int i = 0; i < students.length - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < students.length; j++) {
if (students[j].getName().compareTo(students[minIndex].getName()) < 0) {
minIndex = j;
}
}
Student temp = students[minIndex];
students[minIndex] = students[i];
students[i] = temp;
}
// Print sorted roster
for (int i = 0; i < students.length; i++) {
System.out.println(students[i].getName() + ": " + students[i].getGrade());
}
Output:
Alice: 95
Bob: 91
Charlie: 72
Diana: 88
Quick Check
Q1. When sorting an array of Student objects by grade, what do you compare?
Q2. What does "Apple".compareTo("Banana") return?
Q3. When you swap two Student objects in an array, what actually moves?
Q4. To sort students from highest grade to lowest, what change is needed in the selection sort comparison?
Trace Exercise
Trace one full pass (i=0) of selection sort on these products sorted by price ascending.
Trace: First Pass of Selection Sort (i=0)
// Products: [0] Keyboard $79.99, [1] Mouse $29.99, [2] Monitor $299.99, [3] Webcam $49.99
// i=0, minIndex starts at 0| j | shop[j].getPrice() | shop[minIndex].getPrice() | Update minIndex? | minIndex after |
|---|---|---|---|---|
| 1 | 29.99 | 79.99 | ||
| 2 | 299.99 | |||
| 3 | 49.99 |
After pass: swap index 0 and index . First element becomes:
Spot the Error
This sort should order students alphabetically by name, but it produces the wrong order.
Bug Hunt: A sort that should order students A-Z by name, but uses the wrong comparison operator.
Pick the correct fix for line 5:
Predict the Output
After sorting the products array by price ascending, what is the first line printed by the loop?
// Before sort: Keyboard $79.99, Mouse $29.99, Monitor $299.99, Webcam $49.99
// After selection sort by price ascending:
System.out.println(shop[0].getName() + ": $" + shop[0].getPrice()); Practice Exercises
Core
-
Sort by grade descending – Modify the
sortByGrademethod to sort students from highest grade to lowest. Test with at least 4 students and print the result. -
Sort products by name – Using the
Productclass, write a selection sort that orders products alphabetically by name using.compareTo().
Extension
-
Sort then search – Sort an array of students by name, then write a method that uses binary search (not linear search) to find a student by name. Return the Student object or null.
-
Multi-key sort – Sort students first by house (alphabetical), then by grade (descending) within each house. Students in “Blue” house should appear before “Red” house, and within each house, the highest grade comes first.
Challenge
- Leaderboard – Create a
Playerclass withname,score, andlevel. Maintain a leaderboard of 10 players sorted by score (descending). Write a methodaddPlayer(Player p)that inserts a new player in the correct position (shifting others down) and drops the lowest scorer if the board is full. Do not re-sort the entire array – insert in place.
Connections
- Prerequisites: Sorting Algorithms – selection sort on int arrays
- Prerequisites: Encapsulation – why we use getters instead of direct field access
- Prerequisites: OOP Method Patterns – find-max pattern used in sorting
- Related: Object References – swapping references, not values
- Related: Strings –
.compareTo()for string ordering