Collections.sort Comparator.comparing 冒泡排序 效率对比

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
  public static void main(String[] args) {
            Long t = System.currentTimeMillis();
            Random random = new Random();
            List<Apple> list = new ArrayList<Apple>();
            for (int j = 0; j < 1000000; j++) {
                Apple a = new Apple("Apple"+1,random.nextInt(1000000));
                list.add(a);
            }
            Long t2 = System.currentTimeMillis();
            System.out.println(t2-t);
            //以下四种排序方式,任意打开一个
//          list.sort(java.util.Comparator.comparing(Apple::getWeight));
             
            list.sort((Apple a1, Apple a2)
                    -> a1.getWeight()-a2.getWeight()
                    );
             
//          Collections.sort(list, new Comparator<Apple>() {
//              public int compare(Apple o1, Apple o2) {
//                  return o2.getWeight()-o1.getWeight();
//              }
//          });
             
//          for(int j = 0; j < list.size(); j++){
//              for(int m = j+1; m < list.size(); m++){
//                  Apple a2 = list.get(j);
//                  if(a2.getWeight()>list.get(m).getWeight()){
//                      Apple am = list.get(m);
//                      am.setWeight(a2.getWeight());
//                      a2.setWeight(am.getWeight());
//                  }
//              }
//          }
             
            for (int j = 0; j < 1000000; j++) {
                Apple a = list.get(j);
                //打印验证是否排序成功开关
                //System.out.println(a.getWeight());
            }
            Long t3 = System.currentTimeMillis();
            System.out.println(t3-t2);
             
         
             
        }
<br>结论:不管数据量的多少,用Collections.sort,远优于另外两个,数据量少(万以下,没细测)用冒泡优于Comparator.comparing,数据量最大,冒泡越耗时,综合结论,sort 优于 comparing 优于 冒泡

  

posted on   一个帅哥9527  阅读(6999)  评论(0编辑  收藏  举报
努力加载评论中...

点击右上角即可分享
微信分享提示