I would like to use quicksort to sort my objects.
The object named Person contains two fields (firstname and lastname).
class Person {
private firstName;
private lastName;
//+getter/setter
}
It should be sorted by last name and if last name are same, then by first name.
So if I have Persons ["Miller","Tom"; "Smith","Jerry", "Miller", "Alex"]
the output must be "Miller", "Alex"; "Miller","Tom", "Smith","Jerry".
Sorting by last name works, but I don't know how to realize the second part.
Here the code snippet:
public void quicksort (List<Person> records, int left, int right) {
int index = partition(records, left, right);
if (left < index - 1) {
quicksort (records, left, index - 1);
}
if (index < right) {
quicksort (records, index, right);
}
}
public int partition(List<Person> records, int left, int right) {
int i = left, j = right;
Person tmp;
Person pivot = records.get(left);
while (i <= j) {
while (records.get(i).getLastName().compareTo(pivot.getLastName()) < 0) {
i++;
}
while (records.get(j).getLastName().compareTo(pivot.getLastName()) > 0) {
j--;
}
//TODO: here I need something like if last name same, compare first name
if (i <= j) {
// swap elements
tmp = records.get(i);
records.set(i, records.get(j));
records.set(j, tmp);
i++;
j--;
}
}
return i;
}
Any Idea?