请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

为什么用java实现时要比老师用C++实现时要快一个量级的时间呢?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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;
            }
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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);
    }
}


正在回答 回答被采纳积分+3

插入代码

1回答

liuyubobobo 2017-04-07 13:26:17

有可能你的计算机比我的计算机快一个量级吧!:)我录课用的计算机很老啦,是一台2013年的macbook air:)

0 回复 有任何疑惑可以回复我~
  • 提问者 喜欢蹲门槛的猫 #1
    哦哦,谢谢老师哈,可是还有个问题哈,为什么我用uf2的方法实现比用uf1的方法实现在10万量级的时候要慢一点呢,而且量级越大慢的越多
    回复 有任何疑惑可以回复我~ 2017-04-07 16:36:23
  • liuyubobobo 回复 提问者 喜欢蹲门槛的猫 #2
    那应该是uf2的实现有一些问题哦。不太应该哦。再查查看自己的代码实现有没有问题?尤其可以在代码内加入更多的时间测试,看看具体是那一部分操作拖慢了整体代码的执行速度?
    
    加油!
    回复 有任何疑惑可以回复我~ 2017-04-08 11:26:57
  • 提问者 喜欢蹲门槛的猫 回复 liuyubobobo #3
    老师,我按照您的做法去设置了更多的时间设置,代码和视频对比了下,是完全一样的,最后检查出来UF2的并操作是远快于UF1的并操作的,但是随着量级的增加,特别是在6万以上时,UF2的总体时间就慢于UF1了,应该是UF2的查操作花了很多的时间,会不会是Find方法中的while循环的影响呀?还是其他的什么原因呢?不是很明白了/(ㄒoㄒ)/~~
    回复 有任何疑惑可以回复我~ 2017-04-10 11:36:00
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号