1. 程式人生 > >Java ArrayList Collection.sort排序示例

Java ArrayList Collection.sort排序示例

通過查原始碼(這裡沒有寫出),Collection.sort下的排序實際上是一個MergeSort,歸併排序

以下是一個簡單的double資料排序例子,將double一個個放到Arraylist裡面,然後用Collections.sort排序

如果要對其他資料型別排序也是很簡單的,修改implements Comparator例項的compare方法就行了

程式碼比較明朗,就不多說啦

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class _qsort {
	public final static int ARR_LIMIT = 100;

	public static class DoubleComparator implements Comparator {
		public int compare(Object obj1, Object obj2) {
			Double p1 = (Double) obj1;
			Double p2 = (Double) obj2;
			if (p1 > p2)
				return 1;
			else
				return 0;
		}
	}

	public static void main(String[] args) throws IOException {
		String input_str = "";
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		input_str = br.readLine();
		String[] numb_str = input_str.split(" ");
		ArrayList<Double> numb_double = new ArrayList<Double>();
		for (int i = 0; i < numb_str.length; i++) {
			numb_str[i] = numb_str[i].replace(",", "");//去除輸入的,
			if(!numb_str[i].isEmpty())
				numb_double.add(Double.parseDouble(numb_str[i]));
		}
		DoubleComparator cmp = new DoubleComparator();
		long startTime=System.nanoTime(); 
		Collections.sort(numb_double, cmp);
		long endTime=System.nanoTime();
		System.out.println(numb_double);
		System.out.println("程式執行時間: "+(endTime - startTime) + "ns");
	}
}

一下是輸入1000個0-999隨機數的排序結果: