我的老师教了我Flash排序算法,时间复杂度为O(n)。在运行这个排序算法之前,我需要找出数组中的最大值和最小值。
这是我的解决方案:
//n is a size of array a[]
for(int i = 0; i < n ; i++){
if (_max < a[i]) _max = a[i];
if (_min > a[i]) _min = a[i];
}
假设f(n)是for循环中条件语句的数量(除了比较变量i),所以它的成本为:
- n次比较_max和a[i]
- n次比较_min和a[i]
因此,f(n) = 2n。
我的朋友写了这样的代码:
for(int i = 0; i < n-1; i+=2)
if (a[i] < a[i+1]){
if (_max < a[i+1]) _max = a[i+1];
if (_min > a[i]) _min = a[i];
}
else{
if (_max < a[i]) _max = a[i];
if (_min > a[i+1]) _min = a[i+1];
}
// Compare one more time if n is odd
if (n % 2 == 1){
if (_min > a[n-1]) _min = a[n-1];
if (_max < a[n-1]) _max = a[n-1];
}
我们可以轻松地得到 f'(n) = 3n/2 + 3。当 n 足够大时,似乎有 f'(n) < f(n)。
但是我的老师要求 f(n) = n 或者 f(n) = n + a,其中 a 是一个常数。
有什么好的想法吗?