Java Arrays.sort排序及Comparator自定义排序
这里主要对java内置排序的复习
升序
int[] arr = {
1, 5, 3, 4, 2, 9, 8, 7, 6};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr)); // 输出 1 2 3 4 5 6 7 8 9
来看下sort源码
public static void sort(Object[] a) {
if (LegacyMergeSort.userRequested)
legacyMergeSort(a); // 传统归并排序
else
ComparableTimSort.sort(a, 0, a.length, null, 0, 0); // 优化的归并排序
}
分为传统归并排序和优化的归并排序
打开传统归并的源码
上面写着,将在未来的版本移除,之后可能就没有传统的方法了
/**
* Tuning parameter: list size at or below which insertion sort will be
* used in preference to mergesort.
* To be removed in a future release.
*/
private static final int INSERTIONSORT_THRESHOLD = 7;
/**
* Src is the source array that starts at index 0 -> 原数组
* Dest is the (possibly larger) array destination with a possible offset -> 目标数组
* low is the index in dest to start sorting -> 需要排序的起始下标
* high is the end index in dest to end sorting -> 需要排序的终止下标
* off is the offset to generate corresponding low, high in src -> 偏移量
* To be removed in a future release.
*/
@SuppressWarnings({
"unchecked", "rawtypes"})
private static void mergeSort(Object[] src,
Object[] dest,
int low,
int high,
int off) {
int length = high - low;
// 如果需要排序的长度小于INSERTIONSORT_THRESHOLD,上面定义了为7
// 将每个元素于前面的元素比较,如果小于前面的元素,交换数据
// 相当于插入排序,把小的值放在前面
// Insertion sort on smallest arrays
if (length < INSERTIONSORT_THRESHOLD) {
for (int i=low; i<high; i++)
for (int j=i; j>low &&
((Comparable) dest[j-1]).compareTo(dest[j])>0; j--)
swap(dest, j, j-1);
return;
}
//进行归并排序
// Recursively sort halves of dest into src
int destLow = low;
int destHigh = high;
low += off;
high += off;
int mid = (low + high) >>> 1;
mergeSort(dest, src, low, mid, -off);
mergeSort(dest, src, mid, high, -off);
// If list is already sorted, just copy from src to dest. This is an
// optimization that results in faster sorts for nearly ordered lists.
if (((Comparable)src[mid-1]).compareTo(src[mid]</