public class Main {
public static void main(String[] args) {
Staff[] staffs = new Staff[10];
Staff[] answer = new Staff[staffs.length];
int temp = 0;
staffs[0] = new Staff(1,"J","IT");
staffs[1] = new Staff(3,"I","IT");
staffs[2] = new Staff(2,"H","GA");
staffs[3] = new Staff(7,"G","GA");
staffs[4] = new Staff(5,"F","AUDIT");
staffs[5] = new Staff(6,"E","AUDIT");
staffs[6] = new Staff(4,"D","IT");
staffs[7] = new Staff(10,"C","IT");
staffs[8] = new Staff(9,"B","HR");
staffs[9] = new Staff(8,"A","HR");
PrintArray(staffs);
quickSort(staffs, 0, staffs.length-1);
PrintArray(staffs);
}
private static void quickSort(Staff[] staffs, int start, int end)
{
int i = start;
int j = end;
if (j - i >= 1)
{
String pivot = staffs[i].dep;
while (j > i)
{
while (staffs[i].dep.compareTo(pivot) <= 0 && i < end && j > i){
i++;
}
while (staffs[j].dep.compareTo(pivot) >= 0 && j > start && j >= i){
j--;
}
if (j > i)
swap(staffs, i, j);
}
swap(staffs, start, j);
quickSort(staffs, start, j - 1);
quickSort(staffs, j + 1, end);
}
}
private static void swap(Staff[] staffs, int i, int j)
{
Staff temp = staffs[i];
staffs[i] = staffs[j];
staffs[j] = temp;
}
public static void PrintArray(Staff[] staffs) {
for(int a = 0; a<staffs.length; a++) {
System.out.println(staffs[a].id+", "+staffs[a].name+", "+staffs[a].dep);
}
System.out.println("");
}
}
我在quicksort算法中对这个对象数组进行了排序。它将按部门值进行排序。但问题是有重复的部门值。我想编码,如果部门列中有重复的值,则按id的升序对对象进行排序。
我该怎么办?
1条答案
按热度按时间dfty9e191#
可以在
Staff
类上创建一个compareTo
方法,该方法基于dep
和id
执行比较(当存在平局时):现在,在
quickSort
代码中,只需使用以下方法进行比较: