我有的是算法,它将数组作为参数,并返回其最大值。
find_max(as) :=
max = as[0]
for i = 1 ... len(as) {
if max < as[i] then max = as[i]
}
return max
我的问题是:假设数组最初是(均匀)随机排列的,并且其所有元素都是不同的,那么max
变量被更新的预期次数是多少(忽略初始赋值)。
例如,如果为as = [1, 3, 2]
,则对的更新数max
将为1(读取值3时)。
可以执行和分析许多不同阵列大小的仿真,并进行多次试验:
#include <iostream>
#include <fstream>
#include <cstdlib>
#define UPTO 10000
#define TRIALS 100
using namespace std;
int arr[UPTO];
int main(void){
ofstream outfile ("tabsep.txt");
for(int i = 1; i < UPTO; i++){
int sum = 0;
for(int iter = 0; iter < TRIALS; iter++){
for(int j = 0; j < i; j++){
arr[j] = rand();
}
int max = arr[0];
int times_changed = 0;
for(int j = 0; j < i; j++){
if (arr[j] > max){
max = arr[j];
times_changed++;
}
}
sum += times_changed;
}
int avg = sum/TRIALS;
outfile << i << "\t" << avg << "\n";
cout << "\r" << i;
}
outfile.close();
cout << endl;
return 0;
}
当我绘制这些结果的图形时,复杂度似乎是对数的:
我认为可以断定时间复杂度为O(log n)是安全的。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句