算法导论练习2.2-3算法导论练习2.2-3算法导论练习2.2-
题目是:再次考虑线性查找问题(参见联系2.1-3)。假定要查找的元素等可能地为数组中地任意元素,平均需要检查输入序列地多少元素?最坏情况又如何呢?用θ记号给出线性朝朝地平均情况和最坏情况地运行时间。证明你的答案。
![](https://img.haomeiwen.com/i9907683/0d01a151c78d47da.jpeg)
![](https://img.haomeiwen.com/i9907683/bd175494f0c1886e.png)
![](https://img.haomeiwen.com/i9907683/a67e662fe2a5ada1.png)
![](https://img.haomeiwen.com/i9907683/104f37922418a553.png)
以下是证明过程与C语言程序验证:
![](https://img.haomeiwen.com/i9907683/f1d4ab61c2725091.jpg)
![](https://img.haomeiwen.com/i9907683/fcf76bc2885a9292.png)
![](https://img.haomeiwen.com/i9907683/1078826d71ba231e.png)
![](https://img.haomeiwen.com/i9907683/496b7512c4bae27f.png)
![](https://img.haomeiwen.com/i9907683/1546a80245bfb551.jpg)
![](https://img.haomeiwen.com/i9907683/93cf01f7807d2234.jpeg)
过程中的难点就是等差等比数列的求和,网上搜下公式应该不难。
以下是C语言代码的验证:
````
#include
#include
#include
int main()
{
int v = 23; //v为某个值
int count = 50000; //样本测试的次数
int size = 10; //数组的大小
double p = 0.2; //是v的概率
int h;
double sumIndex = 0;
int arr[size]; //定义数组
srand((unsigned)time(NULL));
for (int k = 0; k < count; k++)
{
for (int i = 0; i < size; i++)
{
if ((double)rand() / RAND_MAX <= p)
{
arr[i] = v;
}
else
{
arr[i] = 1;
}
}
for (int j = 0; j < size; j++)
{
if (arr[j] == v || (j == (size - 1) && arr[j] != v))
{
v = 0;
sumIndex += (j + 1);
break;
}
}
v = 23;
}
printf("%f", (double)(sumIndex / count));
return 0;
}
````
4.459680是大小为10的数组在5w次下的试验平均结果。代入数字,与公式的答案相符。证明完毕。