sorting - 奇偶排序不兼容

标签 sorting java

我是Java新手,我遇到了以下问题。我需要按升序对整数数组进行排序,以便偶数位于一半,奇数位于另一半。

所以,我有一个特殊的比较器:

static class EvenOddSort implements Comparator<Integer> {
    @Override
    public int compare(Integer x, Integer y) {
        if (x == y) {
            return 0;
        }
        if (y % 2 == 0) {
            if (x < y) {
                return -1;
            } else {
                return 1;
            }
        }
        if (x % 2 == 0) {
            if (x < y) {
                return 1;
            } else {
                return -1;
            }
        }
        return 0;
    }
}

以及以下排序方法:

public Integer[] sortEvenOdd(Integer[] nums) {
    EvenOddSort customSort = new EvenOddSort();
    Arrays.sort(nums, customSort);
    return nums;
}

我还有以下测试:

@Test
public void testSortEvenOdd1() {
    Integer[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    Integer[] expected = { 2, 4, 6, 8, 10, 1, 3, 5, 7, 9 };
    assertArrayEquals(expected, tasks5.sortEvenOdd(nums));
}

当我在 openJDK6 上运行时失败,在 openJDK7 上运行成功。

arrays first differed at element [0]; expected:<2> but was:<1> junit.framework.AssertionFailedError: arrays first differed at element [0];     expected:<2> but was:<1>
  • 您能帮助我使其兼容所有 openJDK 吗?
  • 此外,如果知道我做错了什么,那就太好了。

欢迎任何想法!

最佳答案

你的整个比较器坏了,我不断发现它有更多问题。

只需执行以下操作:

if (x%2 != y%2) {
  if (x%2==0) {
     return -1;
  } else {
     return 1;
  }
} else {
  return x.compareTo(y);
}

首先检查它们是否不是都是奇数或都是偶数。如果不同则按奇数或偶数排序。

然后,如果它们都是奇数或都是偶数,则返回到标准整数比较功能。

关于sorting - 奇偶排序不兼容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23735303/

相关文章:

arrays - 你能在快速排序中选择你想要的任何主元吗?

java - 如何使用 Selenium 选择网页中的文本?

java - 对象转换为 Json 字符串并转换回对象失败,缺少 DateTime 元素 Android

java - 为什么在给mvn clean程序包时出现此错误:找不到表?

java - 模拟数据库驱动程序

javascript - 对工作日的对象进行排序,例如星期日、星期一、...、星期六

python - 按值排序字典,然后按键

c - 如何在 C 中对结构数组进行排序?

java - JTable 对整数值排序的问题

java - 为什么我在这两个不同的嵌套 for 循环中得到不同的时间复杂度?