【问题标题】:How to sort by two criteria in JAVA?如何在 JAVA 中按两个条件排序?
【发布时间】:2020-04-08 06:33:58
【问题描述】:

我得到一个 ArrayList ,其中包含下一个数据: coordX 、 coordY 、 length 、 position (位置可以是 3 种类型:垂直、水平或 1x1)。使用插入方法,我按长度降序排序。如果长度与具有水平位置的长度值相等,我如何优先考虑。对于给定的输入:

(1;0)  ,  length = 2  ,  position - vertical
(1;6)  ,  length = 4  ,  position - horizontal
(3;4)  ,  length = 3  ,  position - horizontal
(3;6)  ,  length = 1  ,  position - 1x1
(4;0)  ,  length = 1  ,  position - 1x1
(5;3)  ,  length = 2  ,  position - horizontal
(6;7)  ,  length = 2  ,  position - vertical
(7;5)  ,  length = 2  ,  position - horizontal

输出应该是:

(1;6)  ,  length = 4  ,  position - horizontal
(3;4)  ,  length = 3  ,  position - horizontal
(5;3)  ,  length = 2  ,  position - horizontal
(7;5)  ,  length = 2  ,  position - horizontal
(1;0)  ,  length = 2  ,  position - vertical
(6;7)  ,  length = 2  ,  position - vertical
(3;6)  ,  length = 1  ,  position - 1x1
(4;0)  ,  length = 1  ,  position - 1x1

这是我目前拥有的:

public static void insertionSort(ArrayList<sort> srt) {
        int i,j;
        for (i = 1; i < srt.size(); i++) {
            sort tmp = srt.get(i);
            j = i;
            while ((j > 0) && (srt.get(j - 1).length< tmp.length)) {
                srt.set(j, srt.get(j - 1));
                j--;
            }
            srt.set(j, tmp);
        }
        for(sort e : srt) {
            System.out.println("("+e.coordX+";"+e.coordY+")"+"  ,  length= "+e.length+"  ,  position - "+e.pozitie);
        }

}

这部分代码只负责按长度排序。

【问题讨论】:

标签: java


【解决方案1】:

尝试以下方法:

你需要先检查长度,如果相等,再检查位置。

            while ((j > 0) && (srt.get(j - 1).length < tmp.length
                    || (srt.get(j - 1).length == tmp.length
                            && srt.get(j - 1).position
                                    .compareTo(tmp.position) > 0))) {
                srt.set(j, srt.get(j - 1));
                j--;
            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-06-15
    • 2015-07-03
    • 2018-09-20
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 2017-01-09
    • 2013-09-13
    相关资源
    最近更新 更多