使用随机算法产生一个数,要求把1-1000W之间这些数全部生成

无聊写个玩下

private static void createRandom() {

        Random random = new Random();
        long start = System.currentTimeMillis();

        int value = 10000000;

        ArrayList<Integer> list = new ArrayList<Integer>(value);
        for (int j = 1; j <= value; ++j) {
            list.add(j);
        }

        int index = 0;
        int count = 0;
        int tmp = 0;
        while (value > 0) {
            index = random.nextInt(value);
            // System.out.println(list.get(index));
            tmp = list.get(count + index);
            list.set(count + index, list.get(count));
            list.set(count, tmp);
            ++count;
            --value;
        }

        long end = System.currentTimeMillis();

        //----验证是否正确
        Collections.sort(list);
        int i = 0, size = list.size();
        for (; i < size; ++i) {
            if (list.get(i) != (i + 1))
                System.out.println(i + "error" + list.get(i));
        }
        //----验证是否正确

        System.out.println("creat3------");
        System.out.println("执行耗时 : " + (end - start) / 1000f + " 秒 ");
        System.out.println("集合大小为" + list.size());
    }

private static void createRandom4() {

        Random random = new Random();
        long start = System.currentTimeMillis();

        int value = 10000000;
        //使用数组速度更快
        int[] list = new int[value];

        for (int j = 1; j <= value; ++j) {
            list[j] = j;
        }

        int index = 0;
        int count = 0;
        int tmp = 0;
        while (value > 0) {
            index = random.nextInt(value);
            //System.out.println(list[count + index]);
            tmp = list[count + index];
            list[count + index] = list[count];
            list[count] = tmp;
            ++count;
            --value;
        }

        long end = System.currentTimeMillis();

        //----验证是否正确
        //Collections.sort(list);
        // int i = 0, size = list.length;
        //for (; i < size; ++i) {
        //    if (list[i] != (i + 1))
        //        System.out.println(i + "error" + list[i]);
        // }
        //----验证是否正确

        System.out.println("creat4------");
        System.out.println("执行耗时 : " + (end - start) / 1000f + " 秒 ");
        System.out.println("完了,集合大小为" + list.length);
    }

实际测试结果:
creat3------
执行耗时 : 5.169 秒
完了,集合大小为10000000
creat4------
执行耗时 : 0.729 秒
完了,集合大小为10000000

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值