从源码看Java内置的排序sort()函数

Posted 小崔的技术笔记

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了从源码看Java内置的排序sort()函数相关的知识,希望对你有一定的参考价值。

一般排序算法都是有关数组的排序,而且使用的是随机访问方式。但是对列表进行访问的效率很低。实际上,可以使用归并排序对列表进行高效的排序。然后Java的实现却是:直接将所有元素转入一个数组,对数组进行排序,然后再将排序后的序列复制回列表。

技术分享图片
 1 /**
 2      * Sorts the specified list according to the order induced by the
 3      * specified comparator.  All elements in the list must be <i>mutually
 4      * comparable</i> using the specified comparator (that is,
 5      * {@code c.compare(e1, e2)} must not throw a {@code ClassCastException}
 6      * for any elements {@code e1} and {@code e2} in the list).
 7      *
 8      * <p>This sort is guaranteed to be <i>stable</i>:  equal elements will
 9      * not be reordered as a result of the sort.
10      *
11      * <p>The specified list must be modifiable, but need not be resizable.
12      *
13      * @implNote
14      * This implementation defers to the {@link List#sort(Comparator)}
15      * method using the specified list and comparator.
16      *
17      * @param  <T> the class of the objects in the list
18      * @param  list the list to be sorted.
19      * @param  c the comparator to determine the order of the list.  A
20      *        {@code null} value indicates that the elements‘ <i>natural
21      *        ordering</i> should be used.
22      * @throws ClassCastException if the list contains elements that are not
23      *         <i>mutually comparable</i> using the specified comparator.
24      * @throws UnsupportedOperationException if the specified list‘s
25      *         list-iterator does not support the {@code set} operation.
26      * @throws IllegalArgumentException (optional) if the comparator is
27      *         found to violate the {@link Comparator} contract
28      * @see List#sort(Comparator)
29      */
30     @SuppressWarnings({"unchecked", "rawtypes"})
31     public static <T> void sort(List<T> list, Comparator<? super T> c) {
32         list.sort(c);
33     }
View Code

 

以上是关于从源码看Java内置的排序sort()函数的主要内容,如果未能解决你的问题,请参考以下文章

Arrays.sort解析

内置 qsort 函数和稳定排序函数有啥区别?

写一个二维数组排序算法函数,能够具有通用性,可以调用php内置函数

C++算法从std::sort到排序算法

python 内置排序函数使用

关于Java中Array.sort()排序原理,越详细越好!