java 对象数组中重复值的快速排序

yxyvkwin  于 2023-03-28  发布在  Java
关注(0)|答案(1)|浏览(112)
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的升序对对象进行排序。
我该怎么办?

dfty9e19

dfty9e191#

可以在Staff类上创建一个compareTo方法,该方法基于depid执行比较(当存在平局时):

int compareTo(Staff other) {
        int res = dep.compareTo(other.dep);
        return res != 0 ? res : id - other.id;
    }

现在,在quickSort代码中,只需使用以下方法进行比较:

Staff pivot = staffs[i];
            while (j > i)
            {
                while (staffs[i].compareTo(pivot) <= 0 && i < end && j > i) {
                    i++;
                }
                while (staffs[j].compareTo(pivot) >= 0 && j > start && j >= i) {
                    j--;
                }
                if (j > i)
                    swap(staffs, i, j);
            }

相关问题