0

我有一个冒泡排序函数,它通过“a”变量对 SomeObj 的 LinkedList 进行排序。如果我想同时按“b”变量对列表进行排序怎么办?我能做什么而不是用 b 编写另一个函数?

public static void BubbleSort(LinkedList<SomeObj> objs) {
    int len = objs.size();

    for(int pass = 1; pass < len; pass++) {
        for (int i=0; i < len - pass; i++) {
            if(objs.get(i).a > objs.get(i + 1).a) {
                SomeObj p = objs.get(i);
                objs.set(i,objs.get(i+1));
                objs.set(i + 1, p);
            }
        }
    }
}
4

7 回答 7

4

使用 compare 方法在类中实现 Comparator 接口。接受两个对象并比较它们,返回 -ve,0,+ve 值以告知小于、等于或大于。

创建此 Comparator 的对象并将其传递给冒泡排序方法,并让它使用其比较方法来比较两个对象。

您的对象应该具有所有此类字段的吸气剂。

此外,每当您想更改对象的比较标准时,请使用不同的比较器。

检查这个 例子

于 2012-05-26T22:56:35.533 回答
2

您将让您的 SomeObj 实现该Comparable接口,然后让您的排序使用该接口与它进行交互。

于 2012-05-26T22:55:01.027 回答
2

如果您可以通过第一个“a”进行排序,那么“b”是在您的 SomeObj 类中实现 Comparable 并创建一个比较 a 和 b 的 compareTo 方法。http://www.javapractices.com/topic/TopicAction.do?Id=10

于 2012-05-26T22:57:26.563 回答
1

决定哪个优先级最高。检查更高优先级的变量 - 如果它们不同,只需排序,就好像你只是在排序一样。如果高优先级变量匹配,那么您必须返回到较低优先级的变量,并以此为基础进行整个比较。

if (obj1.getA() != obj2.getA()) {
    // do compare on As
    // e.g. return onj2.getA() - obj1.getA()
}
else { // A's match, so do compares on B
    // e.g. return obj2.getB() - obj1.getB()
}
于 2012-05-26T22:55:23.120 回答
1

我认为最简单的方法是交换变量值而不是列表项。使用这种方法,您可以同时以不同的方式“排序”列表。

于 2012-05-26T22:58:16.047 回答
1

我想有一种误解 - 这不是按 a 排序然后按 b 排序,它是一种 2 个列表合二为一,用户希望对它们进行独立排序但不创建第二个列表,或者我不对?

于 2012-05-26T23:02:45.160 回答
1

对于排序列表,您可以使用

Collections.sort(List list, Comparator c));

就像在这个主要方法中

class Pair{
    int a;
    int b;

    public Pair(int a, int b) {
        this.a=a;
        this.b=b;
    }

    public String toString() {
        // TODO Auto-generated method stub
        return "["+a+","+b+"]";
    }

    //test
    public static void main(String[] args) {
        Comparator<Pair> comparatorA=new Comparator<Pair>() {
            @Override
            public int compare(Pair o1, Pair o2) {
                if (o1.a>o2.a) return 1;
                if (o1.a<o2.a) return -1;
                return 0;
            }
        };
        LinkedList<Pair> list=new LinkedList<>();
        list.add(new Pair(1,2));
        list.add(new Pair(2,1));
        list.add(new Pair(3,1));
        list.add(new Pair(1,3));

        Collections.sort(list, comparatorA);
        System.out.println(list);
    }
}

现在您可以为 b 值制作比较器并将 Collections.sort 与该比较器一起使用

于 2012-05-26T23:10:22.220 回答