Arrays.sort和Collections.sort实现原理解析
Arrays.sort和Collections.sort实现原理解析
1、使用
- 排序
2、原理
事实上Collections.sort方法底层就是调用的array.sort方法,而且不论是Collections.sort或者是Arrays.sort方法,
跟踪下源代码吧,首先我们写个demo
public static void main(String[] args) {
List<String> strings = Arrays.asList("6", "1", "3", "1","2");
Collections.sort(strings);//sort方法在这里
for (String string : strings) {
System.out.println(string);
}
}
简单得不能再简单的方法了,让我们一步步跟踪
- OK,往下面看,发现collections.sort方法调用的list.sort
- 然后跟踪一下,list里面有个sort方法,但是list是一个接口,肯定是调用子类里面的实现,这里我们demo使用的是一个Arrays.asList方法,所以事实上我们的子类就是arraylist了。OK,看arraylist里面sort实现,选择第一个,为什么不选择第二个呢?(可以看二楼评论,解答得很正确,简单说就是用Arrays.sort创建的ArrayList对象)
- OK,发现里面调用的Arrays.sort(a, c); a是list,c是一个比较器,我们来看一下这个方法
我们没有写比较器,所以用的第二项,LegacyMergeSort.userRequested这个bool值是什么呢?
跟踪这个值,我们发现有这样的一段定义:
> Old merge sort implementation can be selected (for
> compatibility with broken comparators) using a system property.
> Cannot be a static boolean in the enclosing class due to
> circular dependencies. To be removed in a future release.
反正是一种老的归并排序,不用管了现在默认是关的
- OK,我们走的是sort(a)这个方法,接着进入这个
- 接着看我们重要的sort方法
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; // array的大小为0或者1就不用排了
// 当数组大小小于MIN_MERGE(32)的时候,就用一个"mini-TimSort"的方法排序,jdk1.7新加
if (nRemaining < MIN_MERGE) {
//这个方法比较有意思,其实就是将我们最长的递减序列,找出来,然后倒过来
int initRunLen = countRunAndMakeAscending(a, lo, hi);
//长度小于32的时候,是使用binarySort的
binarySort(a, lo, hi, lo + initRunLen);
return;
}
//先扫描一次array,找到已经排好的序列,然后再用刚才的mini-TimSort,然后合并,这就是TimSort的核心思想
ComparableTimSort ts = new ComparableTimSort(a, work, workBase, workLen);
int minRun = minRunLength(nRemaining);
do {
// Identify next run
int 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 merge
ts.pushRun(lo, runLen);
ts.mergeCollapse();
// Advance to find next run
lo += runLen;
nRemaining -= runLen;
} while (nRemaining != 0);
// Merge all remaining runs to complete sort
assert lo == hi;
ts.mergeForceCollapse();
assert ts.stackSize == 1;
}
- 回到5,我们可以看到当我们写了比较器的时候就调用了
TimSort.sort方法,源码如下
static <T> void sort(T[] a, int lo, int hi, Comparator<? super T> c,
T[] work, int workBase, int workLen) {
assert c != null && 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 merges
if (nRemaining < MIN_MERGE) {
int initRunLen = countRunAndMakeAscending(a, lo, hi, c);
binarySort(a, lo, hi, lo + initRunLen, c);
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.
*/
TimSort<T> ts = new TimSort<>(a, c, work, workBase, workLen);
int minRun = minRunLength(nRemaining);
do {
// Identify next run
int runLen = countRunAndMakeAscending(a, lo, hi, c);
// 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, c);
runLen = force;
}
// Push run onto pending-run stack, and maybe merge
ts.pushRun(lo, runLen);
ts.mergeCollapse();
// Advance to find next run
lo += runLen;
nRemaining -= runLen;
} while (nRemaining != 0);
// Merge all remaining runs to complete sort
assert lo == hi;
ts.mergeForceCollapse();
assert ts.stackSize == 1;
}
和上面的sort方法是一样的,其实也就是TimSort的源代码
3、总结
不论是Collections.sort方法或者是Arrays.sort方法,底层实现都是TimSort实现的,这是jdk1.7新增的,以前是归并排序。TimSort算法就是找到已经排好序数据的子序列,然后对剩余部分排序,然后合并起来
Arrays.sort和Collections.sort实现原理解析的更多相关文章
- Arrays.sort 与 Collections.sort
代码如下: package com.wangzhu.arrays; import java.util.Arrays; import java.util.Collections; public clas ...
- 48- java Arrays.sort和collections.sort()再次总结
今天又碰到一个新BUG,记下来. 一直报空指针异常,我就很奇怪了,怎么就空指针了呢,我输出时,也能输出东西呀. 原来Arrays.sort() 和 Collections.sort() 都是对整个数组 ...
- 39-java中Arrays.sort 和 collections.sort()总结
总结一下java 中的两种排序工具: Arrays.sort() : 主要针对 数组类型排序,如果数组里面的元素是对象,要按对象属性排序的话,需要重写 Comparator() 函数,重写里面的 i ...
- Java中Arrays.sort()和Collections.sort()
1.简单示例 sort方法的使用非常的简单明了,下面的例子中,先定义一个比较Dog大小的Comparator,然后将其实例对象作为参数传给sort方法,通过此示例,你应该能够快速掌握Arrays.so ...
- sort()排序 collections.sort();
1.main方法: public class Test { public static void main(String[] args) { /** * * sort()方法详解 * 1.Collec ...
- Java8 Collections.sort()及Arrays.sort()中Lambda表达式及增强版Comparator的使用
摘要:本文主要介绍Java8 中Arrays.sort()及Collections.sort()中Lambda表达式及增强版Comparator的使用. 不废话直接上代码 import com.goo ...
- 关于Collections.sort()排序方法的源码探索
/**下面在自己代码中使用Collections.sort()方法去比较Student对象,通过在自己写的类里面通过匿名内部类实现Comparator接口,这个接口是让你自己实现比较器的规则*/ // ...
- Java中Collections.sort()排序详解
public static void main(String[] args) { List<String> list = new ArrayList<String>(); ...
- java中排序函数sort()使用,Arrays.sort()和Collections.sort()
Java中常用的数组或集合排序的方法有两个,一个是java.util.Arrays中的静态方法Arrays.sort(),还有一个是java.util.Collections中的静态方法的Collec ...
随机推荐
- Google官方下拉刷新组件---SwipeRefreshLayout
今天在Google+上看到了SwipeRefreshLayout这个名词,遂搜索了下,发现竟然是刚刚google更新sdk新增加的一个widget,于是赶紧抢先体验学习下. SwipeRefreshL ...
- Android开发之模仿UC浏览器的菜单
这个内容内容涉及到的了两个知识点: PopupWindow:使用PopupWindow创建一个简单的菜单 使用TabHost创建标签:这个网上好多教程随便看看就好. 实现思路: 观察一下UC浏览器的菜 ...
- python练习笔记——分解质因数
分解质因数:输入一个正整数,分解质因数:如输入: 90 则打印: 90 = 2 * 3 * 3 * 5 get_str = input("请输入一个100以内的正整数,以分解质因数:&q ...
- hdu 1280 前m大的数 哈希
前m大的数 Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Subm ...
- Scanner类nextInt方法的使用注意点
一.先看一段正常的代码 1. 一段用Scanner捕获键盘输入的代码: Scanner sc = new Scanner(System.in); // 先读取键盘输入的字符串 System.out.p ...
- 博客目录之C#
C# BackgroundWorker的Bug??? C# BeginInvoke和EndInvoke方法 c# 高效的线程安全队列ConcurrentQueue C# ManualResetEven ...
- Latex算法伪代码使用总结
Latex伪代码使用总结 algorithmicx例子 相应代码: \documentclass[11pt]{ctexart} \usepackage[top=2cm, bottom=2cm, lef ...
- Nginx+mysql+php(待补全)
先安装 Nginx 通过源码安装可以指定目录(/usr/local/Nginx/) yum或源码安装Mysql yum或源码安装php(记得命令一定要全,别忘了安装php-fpm) 待补全
- cocos2dx 3.x designResolutionSize须主动设置
cocos2dx 3.x最初设置screenSize和designResolutionSize的地方如下: bool AppDelegate::applicationDidFinishLaunchin ...
- 在Visual Studio中使用NuGet管理项目库
NuGet是用来管理项目中引用的各个组件插件什么什么东西的东西,最近使用以后发现对于项目引用的维护非常方便. 暂时转一篇MSDN的文章,其实这个文章的内容就够了: http://msdn.micros ...