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

  1. Key Concepts
    1. Why Sort Objects?
    2. Sorting by a Numeric Attribute
    3. Sorting by a String Attribute
    4. How .compareTo() Works
    5. Descending Order
    6. Swapping Object References
  2. Worked Examples
    1. Example 1: Sort Products by Price
    2. Example 2: Sort Students by Name, Then Find Top Grade
  3. Quick Check
  4. Trace Exercise
  5. Spot the Error
  6. Predict the Output
  7. Practice Exercises
    1. Core
    2. Extension
    3. Challenge
  8. 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 of arr[j]
  • The swap moves object references, not primitive values
  • The temp variable is type Student, not int

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 < 0 for ascending (A-Z) and > 0 for 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
jshop[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.

1for (int i = 0; i < count - 1; i++) { 2 int minIndex = i; 3 for (int j = i + 1; j < count; j++) { 4 if (students[j].getName() 5 > students[minIndex].getName()) { 6 minIndex = j; 7 } 8 } 9 Student temp = students[minIndex]; 10 students[minIndex] = students[i]; 11 students[i] = temp; 12}

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

  1. Sort by grade descending – Modify the sortByGrade method to sort students from highest grade to lowest. Test with at least 4 students and print the result.

  2. Sort products by name – Using the Product class, write a selection sort that orders products alphabetically by name using .compareTo().

Extension

  1. 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.

  2. 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

  1. Leaderboard – Create a Player class with name, score, and level. Maintain a leaderboard of 10 players sorted by score (descending). Write a method addPlayer(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


© EduCS.me — A resource hub for IB Computer Science

This site uses Just the Docs, a documentation theme for Jekyll.