用于将零移动到后面的比较器

时间:2014-09-14 14:19:25

标签: java

您好我正在寻找为双打构建比较器,我可以将零移动到列表的后面。

例如

5,2,3,8,0,1

我希望它看起来像这样。

1,2,3,5,8,0

我的比较方法

private Double[] values;

@Override
public int compare(int slot1, int slot2) {
    final Double val1 = values[slot1];
    final Double val2 = values[slot2];
    if (val1 < val2) return -1;
    if (val1 > val2) return 1;
    return 0;
}

如何将零点移到后面?

2 个答案:

答案 0 :(得分:2)

    final Integer[] searchList = new Integer[] { 5, 2, 3, 8, 0, 1 };
    Arrays.sort(searchList, new Comparator<Integer>() {
        @Override
        public int compare(Integer o1, Integer o2) {

            if (o1 == 0) {
                return 1;
            }
            if (o2 == 0) {
                return -1;
            }
            return o1.compareTo(o2);
        }
    });

输入:5,2,3,8,0,1

结果将是:1,2,3,5,8,0

答案 1 :(得分:1)

你甚至可以这样做 只需这个

Double arry[] = {0.0,5.0,2.0,3.0,8.0,0.0,0.0,0.0,1.1,1.0};
Arrays.sort(arry, new Comparator<Double>() {
    public int compare(Double s1, Double s2) {
        if(s1==0.0)
            return 1;
        else if(s2==0.0)
            return -1;
        else if(s1 == 0.0 && s2 == 0.0)
            return 0;
        else
            return s1.compareTo(s2);
    }
});
System.out.println(Arrays.toString(arry));

或者

//first normal sorting
Double arry[] = {0.0,5.0,2.0,3.0,8.0,0.0,0.0,1.0};
Arrays.sort(arry, new Comparator<Double>() {
    public int compare(Double s1, Double s2) {
        if(s1<s2)
            return -1;
        else if(s1>s2)
            return 1;
        else
            return 0;
    }
});
// push the zeros at the end of the array
int count = 0;
int n =arry.length;
for (int i = 0; i < n; i++)
    if (arry[i] != 0)
        arry[count++] = arry[i];
while (count < n)
    arry[count++] = 0.0;
System.out.println(Arrays.toString(arry));