我想使用quicksort来排序我的对象。
名为Person的对象包含两个字段(firstname和lastname)
class Person {
private firstName;
private lastName;
//+getter/setter
}
它应按姓氏排序,如果姓氏相同,则按名字排序。
所以如果我有人["米勒","汤姆&#34 ;; " Smith"," Jerry"," Miller"," Alex"]
输出必须是"米勒","亚历克斯&#34 ;; " Miller"," Tom"," Smith"," Jerry"。
按姓氏排序有效,但我不知道如何实现第二部分。
这里的代码片段:
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;
}
有什么想法吗?
答案 0 :(得分:0)
为您的compareTo
课程定义Person
方法。比较姓氏,如果匹配,则首先命名:
public int compareTo(Person to) {
int cmp = this.lastName.compareTo(to.lastName);
if (cmp == 0)
cmp = this.firstName.compareTo(to.firstName);
return cmp;
}
然后你得到了:
while (records.get(j).compareTo(pivot) > 0) {