为什么用java实现时要比老师用C++实现时要快一个量级的时间呢?
来源:6-2 Quick Find
喜欢蹲门槛的猫
2017-04-07
public class UnionFind { private int[] id; private int count; public UnionFind(int n){ count = n; id = new int[n]; for(int i = 0 ; i < n ; i++){ id[i] = i; } } public int find( int p ){ assert( p >= 0 && p < count); return id[p]; } public boolean isConnected(int p, int q){ return find(p) == find(q); } public void unionElements(int p, int q){ int pId = find(p); int qId = find(q); if(pId == qId){ return; } for(int i = 0 ; i < count ; i++){ if(id[i] == pId){ id[i] = qId; } } } }
import java.util.Random; public class Main { public static void main(String[] args){ int n = 10000; UnionFind uf = new UnionFind(n); Random random = new Random(System.currentTimeMillis()); long start = System.currentTimeMillis(); for(int i = 0 ; i < n ; i++){ int a = random.nextInt(n); int b = random.nextInt(n); uf.unionElements(a, b); } for(int i = 0 ; i < n ; i++){ int a = random.nextInt(n); int b = random.nextInt(n); uf.isConnected(a, b); } long end = System.currentTimeMillis(); System.out.println((double)(end-start)/1000); } }
写回答
1回答
-
liuyubobobo
2017-04-07
有可能你的计算机比我的计算机快一个量级吧!:)我录课用的计算机很老啦,是一台2013年的macbook air:)
052017-04-10
相似问题