algs4 实验题 1.1.39 随机匹配

algs4 实验题 1.1.39 随机匹配

//实验题 1.1.39 随机匹配
public class BinarySearch {
	public static int binary(int[] a, int key) {
		int lo = 0;
		int hi = a.length - 1;
		while(lo <= hi) {
			int mid = (lo + hi)/2;
			if(key == a[mid]) {return mid;}
			if(key > a[mid]) {lo = mid + 1;}
			if(key < a[mid]) {hi = mid - 1;}
		}
		return -1;
	}
	
	public static void main(String[] args) {
		int T = Integer.parseInt(args[0]);
		int N = 1000;
		StdOut.println("When T = " + T);
		
		
		while (N<1000001) 
		{
			int[] num  = new int[T]; // 记录每一遍共有元素的个数
			for (int t = 0;t < T; t++) { //运行T遍
				// 生成两个随机6位正整数数组
				int[] a = new int[N];
				int[] b = new int[N];
				for (int i = 0; i < N; i ++) {
					a[i] = StdRandom.uniform(100000, 1000000);
					b[i] = StdRandom.uniform(100000, 1000000);
				}
				//用二分法查找共有元素
				int count = 0; 
				for (int i = 0; i < N; i++) {
					int key = a[i];
					if (binary(b,key)!=-1) count+=1;
				}
				num[t] = count;
			}
			int sum = 0;
			for (int element:num) {
				StdOut.print(element + "  ");
				sum += element; 
			}
			int average = sum / T;
			StdOut.println("N = " + N + ", " + "The average count = " +  average);
			N *= 10;
		}
	}
}

打印结果

When T = 10
0 0 0 0 0 0 0 0 0 0 N = 1000, The average count = 0
0 0 0 1 0 0 0 0 0 0 N = 10000, The average count = 0
2 0 3 3 0 3 1 2 1 1 N = 100000, The average count = 1
18 13 12 20 16 21 18 28 26 19 N = 1000000, The average count = 19

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值