在工作中,因为很少去查看源码,导致很多问题可能没有深入的研究。毕竟需要有所提高,必须要能够看懂优秀的人写的代码,因此我花时间从JDK源码开始,在看源码时,并以博客方式记载!
(该源码基于JDK1.8版本,与较低版本有较大差别)
一、Arrays.sort方法简介
Sorts the specified range of the specified array of objects according to the order induced by the specified comparator.
The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive.
(If fromIndex==toIndex, the range to be sorted is empty.)
All elements in the range must be mutually comparable by the specified comparator
(that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the range).
This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.
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.
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.
以上大致说了以下几个信息:
1. 排序的元素必须实现Comparable接口,在程序中执行compare方法时 ,一定不能ClassCastException异常。
2. 相等的元素不会进行重排序操作
3. 方法中采用了归并排序方式排序,当数组中部分有序状态是,需要 nlg(n)次比较
4. 当数组中数据基本处于有序状态时,大约需要 n 次比较