java - 如何对两个 ArrayList 进行排序,同时合并为一个?

标签 java sorting arraylist

例如,我有两个 ArrayList:

ArrayList a = new ArrayList();
    a.add(10);
    a.add(35);
    a.add(51);

ArrayList b = new ArrayList();
    b.add(24);
    b.add(46);
    b.add(81);

我需要创建一个函数,它将元素从 B 到 A 放入排序查询中。 (在我看来,它必须检查A和B中相同位置的元素,并将24放在10和35之间,将46放在35和51之间,最后一个是81)。 我有:

 public static void merge(ArrayList a, ArrayList b)
 {
     a.addAll(b);
     Collections.sort(a);
 }

但这不是一个高效的算法(N^2)。 有没有更高效的方法?

最佳答案

来自 List.sort 的文档

This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays.

此实现的复杂度为 O(n lg(n))。大多数时候甚至更低,特别是当输入几乎已排序时。 Java 版本之间的复杂性可能会有所不同,但 O(n lg(n)) 相当可靠。

回到你的算法,我们可以这样说

a.addAll(b); // requires O(n)
Collections.sort(a); // requires O(n lg(n))

所以它永远不会比 O(n lg(n)) 更糟糕。

关于java - 如何对两个 ArrayList 进行排序,同时合并为一个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51649017/

相关文章:

java - Selenium Select 对象的 selectByIndex 方法检查索引属性而不是计数。为什么?

java - 博主 api 帖子图片

java - websphere MQ 消息的格式是什么

java - SQLite中更新语句的问题

java - ArrayList中对象属性值出现的频率

sorting - RDLC 报告没有按照我告诉它的方式排序

javascript - 创建 DOM 元素之前如何按日期排序

php - 在 PHP/MySql 中对来自不同查询的表数据进行排序

java - 流收集方法的有效供应商

javascript - 如何使用 jQuery 创建数组列表的对象