Java Collections类排序学习

jdk自带排序学习,比如我们写一个排序代码

       List score = new ArrayList();score.add(1);score.add(12);score.add(45);score.add(67);Collections.sort(score);

来看一下sort的实现

    /*** Sorts the specified list into ascending order, according to the* {@linkplain Comparable natural ordering} of its elements.* All elements in the list must implement the {@link Comparable}* interface.  Furthermore, all elements in the list must be* <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)}* must not throw a {@code ClassCastException} for any elements* {@code e1} and {@code e2} in the list).** <p>This sort is guaranteed to be <i>stable</i>:  equal elements will* not be reordered as a result of the sort.** <p>The specified list must be modifiable, but need not be resizable.** @implNote* This implementation defers to the {@link List#sort(Comparator)}* method using the specified list and a {@code null} comparator.** @param  <T> the class of the objects in the list* @param  list the list to be sorted.* @throws ClassCastException if the list contains elements that are not*         <i>mutually comparable</i> (for example, strings and integers).* @throws UnsupportedOperationException if the specified list's*         list-iterator does not support the {@code set} operation.* @throws IllegalArgumentException (optional) if the implementation*         detects that the natural ordering of the list elements is*         found to violate the {@link Comparable} contract* @see List#sort(Comparator)*/@SuppressWarnings("unchecked")public static <T extends Comparable<? super T>> void sort(List<T> list) {list.sort(null);}

继续跟进

    /*** Sorts this list according to the order induced by the specified* {@link Comparator}.** <p>All elements in this list must be <i>mutually comparable</i> using the* specified comparator (that is, {@code c.compare(e1, e2)} must not throw* a {@code ClassCastException} for any elements {@code e1} and {@code e2}* in the list).** <p>If the specified comparator is {@code null} then all elements in this* list must implement the {@link Comparable} interface and the elements'* {@linkplain Comparable natural ordering} should be used.** <p>This list must be modifiable, but need not be resizable.** @implSpec* The default implementation obtains an array containing all elements in* this list, sorts the array, and iterates over this list resetting each* element from the corresponding position in the array. (This avoids the* n<sup>2</sup> log(n) performance that would result from attempting* to sort a linked list in place.)** @implNote* 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.** <p>The implementation takes equal advantage of ascending and* descending order in its input array, and can take advantage of* ascending and descending order in different parts of the same* input array.  It is well-suited to merging two or more sorted arrays:* simply concatenate the arrays and sort the resulting array.** <p>The implementation was adapted from Tim Peters's list sort for Python* (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">* TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic* Sorting and Information Theoretic Complexity", in Proceedings of the* Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,* January 1993.** @param c the {@code Comparator} used to compare list elements.*          A {@code null} value indicates that the elements'*          {@linkplain Comparable natural ordering} should be used* @throws ClassCastException if the list contains elements that are not*         <i>mutually comparable</i> using the specified comparator* @throws UnsupportedOperationException if the list's list-iterator does*         not support the {@code set} operation* @throws IllegalArgumentException*         (<a href="Collection.html#optional-restrictions">optional</a>)*         if the comparator is found to violate the {@link Comparator}*         contract* @since 1.8*/@SuppressWarnings({"unchecked", "rawtypes"})default void sort(Comparator<? super E> c) {Object[] a = this.toArray();Arrays.sort(a, (Comparator) c);ListIterator<E> i = this.listIterator();for (Object e : a) {i.next();i.set((E) e);}}
    /*** Sorts the specified array of objects according to the order induced by* the specified comparator.  All elements in the array must be* <i>mutually comparable</i> by the specified comparator (that is,* {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}* for any elements {@code e1} and {@code e2} in the array).** <p>This sort is guaranteed to be <i>stable</i>:  equal elements will* not be reordered as a result of the sort.** <p>Implementation note: 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.** <p>The implementation takes equal advantage of ascending and* descending order in its input array, and can take advantage of* ascending and descending order in different parts of the the same* input array.  It is well-suited to merging two or more sorted arrays:* simply concatenate the arrays and sort the resulting array.** <p>The implementation was adapted from Tim Peters's list sort for Python* (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">* TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic* Sorting and Information Theoretic Complexity", in Proceedings of the* Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,* January 1993.** @param <T> the class of the objects to be sorted* @param a the array to be sorted* @param c the comparator to determine the order of the array.  A*        {@code null} value indicates that the elements'*        {@linkplain Comparable natural ordering} should be used.* @throws ClassCastException if the array contains elements that are*         not <i>mutually comparable</i> using the specified comparator* @throws IllegalArgumentException (optional) if the comparator is*         found to violate the {@link Comparator} contract*/public static <T> void sort(T[] a, Comparator<? super T> c) {if (c == null) {sort(a);} else {if (LegacyMergeSort.userRequested)legacyMergeSort(a, c);elseTimSort.sort(a, 0, a.length, c, null, 0, 0);}}

如果没有自定义排序就执行默认排序

    /*** Sorts the specified array of objects into ascending order, according* to the {@linkplain Comparable natural ordering} of its elements.* All elements in the array must implement the {@link Comparable}* interface.  Furthermore, all elements in the array must be* <i>mutually comparable</i> (that is, {@code e1.compareTo(e2)} must* not throw a {@code ClassCastException} for any elements {@code e1}* and {@code e2} in the array).** <p>This sort is guaranteed to be <i>stable</i>:  equal elements will* not be reordered as a result of the sort.** <p>Implementation note: 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.** <p>The implementation takes equal advantage of ascending and* descending order in its input array, and can take advantage of* ascending and descending order in different parts of the the same* input array.  It is well-suited to merging two or more sorted arrays:* simply concatenate the arrays and sort the resulting array.** <p>The implementation was adapted from Tim Peters's list sort for Python* (<a href="http://svn.python.org/projects/python/trunk/Objects/listsort.txt">* TimSort</a>).  It uses techniques from Peter McIlroy's "Optimistic* Sorting and Information Theoretic Complexity", in Proceedings of the* Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474,* January 1993.** @param a the array to be sorted* @throws ClassCastException if the array contains elements that are not*         <i>mutually comparable</i> (for example, strings and integers)* @throws IllegalArgumentException (optional) if the natural*         ordering of the array elements is found to violate the*         {@link Comparable} contract*/public static void sort(Object[] a) {if (LegacyMergeSort.userRequested)legacyMergeSort(a);elseComparableTimSort.sort(a, 0, a.length, null, 0, 0);}/** To be removed in a future release. */private static void legacyMergeSort(Object[] a) {Object[] aux = a.clone();mergeSort(aux, a, 0, a.length, 0);}

legacyMergeSort 归并排序默认关闭的,重点关注 ComparableTimSort.sort

    /*** Sorts the given range, using the given workspace array slice* for temp storage when possible. This method is designed to be* invoked from public methods (in class Arrays) after performing* any necessary array bounds checks and expanding parameters into* the required forms.** @param a the array to be sorted* @param lo the index of the first element, inclusive, to be sorted* @param hi the index of the last element, exclusive, to be sorted* @param work a workspace array (slice)* @param workBase origin of usable space in work array* @param workLen usable size of work array* @since 1.8*/static void sort(Object[] a, int lo, int hi, Object[] work, int workBase, int workLen) {assert a != null && lo >= 0 && lo <= hi && hi <= a.length;int nRemaining  = hi - lo;if (nRemaining < 2)return;  // Arrays of size 0 and 1 are always sorted// If array is small, do a "mini-TimSort" with no mergesif (nRemaining < MIN_MERGE) {int initRunLen = countRunAndMakeAscending(a, lo, hi);binarySort(a, lo, hi, lo + initRunLen);return;}/*** March over the array once, left to right, finding natural runs,* extending short natural runs to minRun elements, and merging runs* to maintain stack invariant.*/ComparableTimSort ts = new ComparableTimSort(a, work, workBase, workLen);int minRun = minRunLength(nRemaining);do {// Identify next runint runLen = countRunAndMakeAscending(a, lo, hi);// If run is short, extend to min(minRun, nRemaining)if (runLen < minRun) {int force = nRemaining <= minRun ? nRemaining : minRun;binarySort(a, lo, lo + force, lo + runLen);runLen = force;}// Push run onto pending-run stack, and maybe mergets.pushRun(lo, runLen);ts.mergeCollapse();// Advance to find next runlo += runLen;nRemaining -= runLen;} while (nRemaining != 0);// Merge all remaining runs to complete sortassert lo == hi;ts.mergeForceCollapse();assert ts.stackSize == 1;}

如果小于 private static final int MIN_MERGE = 32;大小就进行折半插入排序,如果大于32进行

TimSort排序

    /*** Sorts the given range, using the given workspace array slice* for temp storage when possible. This method is designed to be* invoked from public methods (in class Arrays) after performing* any necessary array bounds checks and expanding parameters into* the required forms.** @param a the array to be sorted* @param lo the index of the first element, inclusive, to be sorted* @param hi the index of the last element, exclusive, to be sorted* @param work a workspace array (slice)* @param workBase origin of usable space in work array* @param workLen usable size of work array* @since 1.8*/static void sort(Object[] a, int lo, int hi, Object[] work, int workBase, int workLen) {assert a != null && lo >= 0 && lo <= hi && hi <= a.length;int nRemaining  = hi - lo;if (nRemaining < 2)return;  // Arrays of size 0 and 1 are always sorted// If array is small, do a "mini-TimSort" with no mergesif (nRemaining < MIN_MERGE) {int initRunLen = countRunAndMakeAscending(a, lo, hi);binarySort(a, lo, hi, lo + initRunLen);return;}/*** March over the array once, left to right, finding natural runs,* extending short natural runs to minRun elements, and merging runs* to maintain stack invariant.*/ComparableTimSort ts = new ComparableTimSort(a, work, workBase, workLen);int minRun = minRunLength(nRemaining);do {// Identify next runint runLen = countRunAndMakeAscending(a, lo, hi);// If run is short, extend to min(minRun, nRemaining)if (runLen < minRun) {int force = nRemaining <= minRun ? nRemaining : minRun;binarySort(a, lo, lo + force, lo + runLen);runLen = force;}// Push run onto pending-run stack, and maybe mergets.pushRun(lo, runLen);ts.mergeCollapse();// Advance to find next runlo += runLen;nRemaining -= runLen;} while (nRemaining != 0);// Merge all remaining runs to complete sortassert lo == hi;ts.mergeForceCollapse();assert ts.stackSize == 1;}

Timsort是一个自适应的、混合的、稳定的排序算法,是由Tim Peter于2002年发明的,最早应用在Python中,现在广泛应用于Python、Java、Android 等语言与平台中,作为基础的排序算法使用。其中Java语言的Collection.sort在JDK1.6使用的是普通的归并排序,归并排序虽然时间复杂度低,但是空间复杂度要求较高,所以从JDK1.7开始就更改为了TimSort算法。

Timsort 的时间复杂度是 O(n log n),与归并排序的时间复杂度相同,那它的优势是啥呢,实际上可以认为TimSort排序算法是归并排序算法的优化版,从它的三个特征就可以看出,第二个特征“混合的”,没错,它不单纯是一种算法,而是融合了归并算法和二分插入排序算法的精髓,因此能够在排序性能上表现优异。

总结:排序->自定义接口实现排序->归并排序->折半插入排序->TImSort

欢迎指正交流

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/606041.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

系统编程--VIM特辑

这里写目录标题 vim三种工作模式进入文本模式的快捷键在命令模式下进行文本编辑删除快捷键复制粘贴查找替换查找替换 vim其他操作 vim打造简易IDE vim 三种工作模式 具体可见第二章对vim的详细介绍 需要注意的是&#xff0c;在末行模式下执行完一次命令&#xff0c;就可以直接…

企业进行股权众筹的时候要注意哪些问题?

1. 目标与风险 首先&#xff0c;企业要明确众筹的目标和期望。股权众筹不仅是为了筹集资金&#xff0c;更是为了扩大人脉、增加品牌曝光度。因此&#xff0c;企业在发起众筹时&#xff0c;应制定详细的计划和目标&#xff0c;并对可能出现的风险进行充分评估。例如&#xff0c;…

编写.NET的Dockerfile文件构建镜像

创建一个WebApi项目&#xff0c;并且创建一个Dockerfile空文件&#xff0c;添加以下代码&#xff0c;7.0代表的你项目使用的SDK的版本&#xff0c;构建的时候也需要选择好指定的镜像tag FROM mcr.microsoft.com/dotnet/aspnet:7.0 AS base WORKDIR /app EXPOSE 80 EXPOSE 443F…

报表控件Stimulsoft 2023回顾:都做了哪些产品的改变?

在2023年过去一年中&#xff0c;报表控件Stimulsoft 针各类控件都做了重大改变&#xff0c;其中新增了某些产品、同时加强了很多产品的性能和UI设计&#xff0c;更加符合开发者需求&#xff0c;下面就跟随小编一起来回顾&#xff0c;具体都有哪些↓↓↓ Stimulsoft Ultimate &…

uniapp打包后图片资源会重复

hbuildx打包后文件过大&#xff0c;多方优化后&#xff0c;发现会生成重复的图片&#xff0c;如图&#xff1a; 临时解决方法&#xff1a; lib.zip chain-webpack.js_.zip 解压 lib.zip 替换到 HBuilderX根目录/plugins/uniapp-cli/node_modules/dcloudio/uni-cli-shared/lib…

【无标题】MySQL8修改非root用户密码

首先查看修改的用户信息&#xff0c;我这里用户名是demo&#xff0c;host是**%** 然后使用alter命令修改密码 这里USER后的参数是第一步里查询得到的user与host的组合。ALTER USER demo% IDENTIFIED WITH mysql_native_password BY 新密码;可能会出现的错误&#xff1a; 如果百…

DNS被劫持怎么办

DNS劫持是一种网络攻击&#xff0c;攻击者通过篡改DNS记录&#xff0c;将特定域名的解析结果指向错误的IP地址&#xff0c;从而实现对特定网站的访问劫持或流量劫持。这种攻击方式严重影响了用户的上网体验&#xff0c;并可能导致用户隐私泄露。下面也从原因、危害以及应对的策…

Spring中的工厂类

目录 1.ApplicationContext 4.2.BeanFactory 1.ApplicationContext ApplicationContext的实现类&#xff0c;如下图&#xff1a; ClassPathXmlApplicationContext&#xff1a;加载类路径下 Spring 的配置文件 FileSystemXmlApplicationContext&#xff1a;加载本地磁盘下 S…

TypeScript 从入门到进阶之基础篇(五) 枚举类型篇

系列文章目录 TypeScript 从入门到进阶系列 TypeScript 从入门到进阶之基础篇(一) ts基础类型篇TypeScript 从入门到进阶之基础篇(二) ts进阶类型篇TypeScript 从入门到进阶之基础篇(三) 元组类型篇TypeScript 从入门到进阶之基础篇(四) symbol类型篇 持续更新中… 文章目录 …

Ubuntu安装Anaconda并创建虚拟环境

1. 在Index of /anaconda/archive/ | 清华大学开源软件镜像站 | Tsinghua Open Source Mirror页面的中后部找到相应Server的最新版本。 2. 点击下载发文时的最新版本Anaconda3-2023.09-0-Linux-x86_64.sh。 3. 上传后&#xff0c;执行bash Anaconda3-2023.09-0-Linux-x86_64.…

【性能测试入门】:压力测试概念!

压力测试可以验证软件应用程序的稳定性和可靠性。压力测试的目标是评估软件在极端负载条件下的鲁棒性和错误处理能力&#xff0c;并确保软件在紧急情况下不会崩溃。它甚至可以进行超出软件正常工作条件的测试&#xff0c;并评估软件在极端条件下的工作方式。 在软件工程中&…

Arrays 的使用

Arrays 概述 提供了数组操作的相关方法&#xff0c;连接数组和集合 asList 返回指定数组的列表列表和数组的引用位置相同 Integer[] arrs new Integer[] {1,2,3,4,5,6,7,8,9};List<Integer> list Arrays.asList(arrs);System.out.println(list);arrs[5] 100;Syste…

【设计模式之美】SOLID 原则之二:开闭原则方法论、开闭原则如何取舍

文章目录 一. 如何理解“对扩展开放、修改关闭”&#xff1f;二. 修改代码就意味着违背开闭原则吗&#xff1f;三. 如何做到“对扩展开放、修改关闭”&#xff1f;四. 如何在项目中灵活应用开闭原则&#xff1f; 一. 如何理解“对扩展开放、修改关闭”&#xff1f; 具体的说&a…

如何判断模型陷入局部最优解的陷阱?

判断一个模型是否陷入了局部最优解的陷阱并不总是直观的&#xff0c;但有一些迹象和方法可以帮助我们做出判断&#xff1a; 训练进程停滞&#xff1a; 如果模型的训练误差或验证误差在经过多次迭代后停止改善或改善非常缓慢&#xff0c;这可能是一个迹象。 训练和验证误差的差…

欠拟合与过拟合

在模型训练中&#xff0c;我们总是希望最终的模型在训练集上有很好的拟合即训练误差小&#xff0c;同时在测试集上也要有较好的拟合效果即泛化误差小&#xff0c;但往往不尽人意。 总之&#xff0c;模型的训练是一个不断调整和优化的过程&#xff0c;我们需要根据实际情况选择合…

【EI会议征稿通知】第三届城市规划与区域经济国际学术会议(UPRE 2024)

第三届城市规划与区域经济国际学术会议&#xff08;UPRE 2024&#xff09; 2024 3rd International Conference on Urban Planning and Regional Economy 第三届城市规划与区域经济国际学术会议&#xff08;UPRE 2024&#xff09;于2024年4月19-21日在泰国曼谷举行。会议旨在…

【MySQL】分组(group by)后再筛选(having)巧用 sum(条件表达式) 语法

力扣题 1、题目地址 1083. 销售分析 II 2、模拟表 表&#xff1a;Product Column NameTypeproduct_idintproduct_namevarcharunit_priceint Product_id 是该表的主键(具有唯一值的列)。该表的每一行表示每种产品的名称和价格。 表&#xff1a;Sales Column NameTypesel…

Studio 3T客户端连接Mongodb数据库服务

这里需要注意 一定要先开Studio 3T 到 创建连接时才开Mongodb服务 不然 Studio 3T 会找不到Mongodb服务 不知道这是不是 Studio 3T官方问题 期待解决吧 我们打开 Studio 3T 然后点击 Create a new connection 开始创建连接 新弹出的窗口中选择 Manually configure my connec…

实验4.4 动态路由OSPF协议的配置

实验4.4 动态路由OSPF协议的配置 一、任务描述二、任务分析三、具体要求四、实验拓扑五、任务实施1.配置交换机和路由器的接口的IP地址等参数。2.配置动态路由OSPF协议&#xff0c;实现全网互通。 六、任务验收七、任务小结八、知识链接1&#xff0e;OSPF协议概念2&#xff0e;…

MessageBox打通数字通信:深度解析HubSpot与微信群的无缝对接

在当今数字化时代&#xff0c;企业追求更高效的客户互动方式。HubSpot作为综合性的市场营销、销售和服务平台&#xff0c;其与微信群的无缝对接成为企业数字化沟通的重要一环。今天运营坛将深度解析HubSpot如何精准对接微信群&#xff0c;并着重探讨MessageBox在这一过程中的关…