import java.util.*;
public class HashSetSort {
public static void main (String args[]){
HashSet hs = new HashSet() ;
//产生1000个值不相同的随机数
while (hs.size() < 1000) {
hs.add((int)(Math.random()*2000)) ;
}
long startTime = System.currentTimeMillis() ; //获取开始排序时的时间
//申明一个数组,使用一个循环,将随机产生的1000个数据排序并且存储到数组中
int d[] = new int[2000] ; //注意这里的数组大小是2000,因为随机数是0~2000之间的数
for (Object v: hs) {
Integer v1=Integer.parseInt(v.toString());
d[v1.intValue()] = v1.intValue() ;
}
//将数组中的0值丢弃,申明一个ArrayList,用来存放处理后的剩余数据
ArrayList al = new ArrayList() ;
for (int i = 0 ; i < 2000 ; i++) { //注意这里的循环大小是2000,d数组的大小的2000
if (d[i] != 0) {
al.add(d[i]) ;
}
}
//如果随机数中有0值,就需要将这个被丢弃的0值加到ArrayList中
if (al.size() < 1000) {
al.add(0) ;
}
//打印出排序1000个数据的时间,相比之下,这会给了我一个惊喜
System.out.println("排序1000个数据所用的时间:"+(System.currentTimeMillis() - startTime)+"ms") ;
}
}
Baidu:Java中一个巧妙的排序算法