class Person {
private String lastName;
private String firstName;
private int age;
public Person(String last, String first, int a) {
lastName = last;
firstName = first;
age = a;
}
public String toString() {
return "Last name: " + lastName + " First name: " + firstName + " Age: " + age;
}
public String getLast() {
return lastName;
}
}
public class MainClass {
public static void main(String[] args) {
Person[] persons = new Person[] {
new Person("a", "b", 23),
new Person("i", "a", 25),
new Person("y", "h", 26),
new Person("d", "e", 27) };
System.out.println("Before sorting:");
for (Person p : persons) {
System.out.println(p);
}
insertionSort(persons);
System.out.println("After sorting:");
for (Person p : persons) {
System.out.println(p);
}
}
public static void insertionSort(Person[] persons) {
int in, out;
for (out = 1; out < persons.length; out++) {
Person temp = persons[out];
in = out;
while (in > 0 && persons[in - 1].getLast().compareTo(temp.getLast()) > 0) {
persons[in] = persons[in - 1];
--in;
}
persons[in] = temp;
}
}
}
|