码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-08-21 22:36:39      阅读:443      评论:0      收藏:0      [点我收藏+]

标签:sorted   public   argument   The   col   table   方式   view   tee   

一般排序算法都是有关数组的排序,而且使用的是随机访问方式。但是对列表进行访问的效率很低。实际上,可以使用归并排序对列表进行高效的排序。然后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()函数

标签:sorted   public   argument   The   col   table   方式   view   tee   

原文地址:https://www.cnblogs.com/code4her/p/9514530.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!