【问题标题】:Arrays.parallelSort vs Collections.sortArrays.parallelSort vs Collections.sort
【发布时间】:2014-11-30 09:28:22
【问题描述】:

我正在检查一个想知道如何使用Comparatorpost 和一个橙色 水果一直是第一个。从帖子中缺少 toString 方法,所以我添加到我的代码中

@Override
public String toString(){
    return fruitName +"  " + fruitDesc;
}

帖子给出的答案是

使用 Collection.sort

Collections.sort(fruits, new Comparator<Fruit>() {
        @Override
        public int compare(Fruit o1, Fruit o2) {
            if (o1.getFruitName() != null && o1.getFruitName().equalsIgnoreCase("orange")){
                return -1;
            }

            if (o2.getFruitName() != null && o2.getFruitName().equalsIgnoreCase("orange")){
                return 1;
            }

            return o1.getFruitName().compareTo(o2.getFruitName());
        }
    }); 

输出

Orange  Orange description
Apple  Apple description
Banana  Banana description
Pineapple  Pineapple description

我在想为什么不Arrays.parallelSort 我听说过很好的东西

read more here

使用Arrays.parallelSort 代码

 Fruit[] arrayFruits = fruits.stream().toArray(Fruit[]::new);
 Arrays.parallelSort(arrayFruits, (Fruit o1, Fruit o2) -> {
     if (o1.getFruitName() != null && o1.getFruitName().equalsIgnoreCase("orange")){
         return -1;
     }
     if (o2.getFruitName() != null && o2.getFruitName().equalsIgnoreCase("orange")){
         return 1;
     }
      return o1.getFruitName().compareTo(o2.getFruitName());
    });  

输出

Pineapple  Pineapple description
Apple  Apple description
Orange  Orange description
Banana  Banana description

The link to the post is here

对我来说排序就是排序,为什么不同的答案形成不同的方法?

【问题讨论】:

  • 这些link1link2 对您有帮助吗?
  • @ankur-singhal 谢谢你,但我已经检查过了
  • @KickButtowski:你确定你正确地运行了程序。无论我输入值的顺序如何,Orange 都会排在第一位。
  • @Ya 我确定你看到帖子了
  • 对我来说也一样:无法复制它。橙色是第一位的。

标签: java sorting java-8


【解决方案1】:

如果在TryJava8 中运行程序,我会得到正确排序的数组。我认为您可能打印了输入 (fruits) 而不是输出 (arrayFruits)。这就是说,你打开了一个有趣的话题,因为一般来说,你是对的,排序算法并不能保证完整的顺序。一般来说,对于大型数组,如果两个元素是等价的,但不相同(例如指向等价记录的不同指针),则算法不保证特定的顺序。这所说的关系通常被不同的算法以不同的方式打破。

比较方法应满足顺序关系约束

顺序关系应该是:

  • 自反:每个项目都应该等于它自己(我猜你最好返回0
  • 不对称:如果A小于或等于BB小于或等于A, AB 是相等的。
  • 传递性:如果A小于或等于BB小于或等于CA小于等于C

大多数排序算法都隐含地假设了这个约束(他们不检查它们),因此提供了 O(n log n) 的时间复杂度。如果条件不成立,根据算法的实现,得到不同的结果。

由于并行排序使用MergeSort 算法,而默认排序使用QuickSort 算法,因此这两种算法具有不同的行为。

一个相关主题:大多数排序算法都不稳定。假设两个项目“相等”,则不能保证如果在原始数组中将 A 放在 A' 之前,则 A 将是在结果数组中放置在 A' 之前。

【讨论】:

  • 结果必须相同。根据帖子,橙色必须始终排在第一位
  • 好吧,但请注意,对于大型数组,“等价”的项目(但不相同,例如不同的指针)可以被打乱...
  • 非常感谢您的回答,这对您很有帮助:)
  • “默认”使用QuickSort,因为QuickSort 不是一个稳定的算法,Collections.sort 保证是稳定的。 QuickSort 可能用于排序的稳定性没有意义的地方,例如在对像Arrays.sort(int[]) 这样的数字进行排序时。值得注意的是,问题的比较器确实违反了Comparator 的约定,因为它没有正确处理两个元素都具有名称"orange" 的情况。
猜你喜欢
  • 1970-01-01
  • 2015-07-15
  • 2013-06-24
  • 2020-03-19
  • 2015-02-21
  • 2018-06-05
  • 2012-12-28
  • 2011-02-22
相关资源
最近更新 更多