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


  
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);
			
		
			
		}

  


結論:不管數據量的多少,用Collections.sort,遠優於另外兩個,數據量少(萬以下,沒細測)用冒泡優於Comparator.comparing,數據量最大,冒泡越耗時,綜合結論,sort 優於 comparing 優於 冒泡


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM