第一次写博客哈,今天突发奇想去看了下Arrays.sort()方法得源码,就简单写写关于对源码的理解。
这里简单说一下,Arrays.sort(int[] a)方法其实是调用了DualPivotQuicksort.sort()方法,在DualPivotQuicksort类中sort()方法有对每种数据类型有两个重载函数,而当数组的长度小于286时,会调用带有四个参数的sort()方法,该方法主要使用的是优化过后的插入排序算法,其最坏情况的时间复杂度虽然仍然是O( n2 ),但相对于普通的插入排序算法来说,要节省了将近一半的时间。
以下是源码
//在此处跳过前面的升序排列
do {
if (left >= right) {
return;
}
} while (a[++left] >= a[left - 1]);
/*
* Every element from adjoining part plays the role
* of sentinel, therefore this allows us to avoid the
* left range check on each iteration. Moreover, we use
* the more optimized algorithm, so called pair insertion
* sort, which is faster (in the context of Quicksort)
* than traditional implementation of insertion sort.
*/
//在这段代码中以中间数为游标,一次循环里将三个数排好序并
//将较小的两个数插入到前面的序列中排好序(先找到较大数的插入点)
//插入较大数后再往前查找最小数插入点
for (int k = left; ++left <= right; k = ++left) {
int a1 = a[k], a2 = a[left];
if (a1 < a2) {
a2 = a1; a1 = a[left];
}
while (a1 < a[--k]) {
a[k + 2] = a[k];
}
a[++k + 1] = a1;
while (a2 < a[--k]) {
a[k + 1] = a[k];
}
a[k + 1] = a2;
}
int last = a[right];
while (last < a[--right]) {
a[right + 1] = a[right];
}
a[right + 1] = last;