Arrays.parallelSort vs Collections.sort

Kic*_*ski 5 java sorting java-8

我正在检查一篇想知道如何使用的帖子,Comparator并且一直都是橙色水果.从帖子toString方法丢失所以我添加到我的代码

@Override
public String toString(){
    return fruitName +"  " + fruitDesc;
}
Run Code Online (Sandbox Code Playgroud)

帖子的答案是

使用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());
        }
    }); 
Run Code Online (Sandbox Code Playgroud)

输出:

Orange  Orange description
Apple  Apple description
Banana  Banana description
Pineapple  Pineapple description
Run Code Online (Sandbox Code Playgroud)

我在想为什么不 Arrays.parallelSort被告知我的好东西

在这里阅读更多

使用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());
    });  
Run Code Online (Sandbox Code Playgroud)

输出:

Pineapple  Pineapple description
Apple  Apple description
Orange  Orange description
Banana  Banana description
Run Code Online (Sandbox Code Playgroud)

这篇文章的链接就在这里

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

Wil*_*sem 4

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

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

顺序关系应该是:

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

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

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

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

  • “默认”不*使用“QuickSort”,因为“QuickSort”不是稳定的算法,而“Collections.sort”保证稳定。当排序的稳定性没有意义时,可以使用“QuickSort”,例如像“Arrays.sort(int[])”那样对数字进行排序时。值得注意的是,问题的比较器确实违反了“Comparator”的约定,因为它没有正确处理两个元素都具有名称““orange””的情况。 (3认同)