通过查源码(这里没有写出),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随机数的排序结果: