我正在比较 maxmin 算法实现的复杂性,我以两种方式实现:蛮力方式和分而治之的方式。在我为 1000000 和 10000000 之间的十个元素输入测试了这两种算法之后。遵循以下算法:
下面的蛮力实现:
def maxmin1(vetor):
max,min = vetor[0],vetor[0];
for elem in vetor[1:]:
if elem > max:
max = elem
if elem < min:
min = elem
return (min,max)
和下面的分而治之的实现:
def maxmin4(vetor,inicio,fim):
if ((fim - inicio) == 1):
return (vetor[inicio], vetor[inicio])
elif ((fim - inicio) == 2):
if( vetor[inicio] < vetor[inicio+1]):
return (vetor[inicio], vetor[inicio+1])
else:
return (vetor[inicio+1], vetor[inicio])
else:
(min_left,max_left) = maxmin4(vetor,inicio,(fim-inicio)/2 + inicio)
(min_right,max_right) = maxmin4(vetor,(fim-inicio)/2 + inicio,fim)
if (max_left < max_right):
max = max_right
else:
max = max_left
if (min_left < min_right):
min = min_left
else:
min = min_right
return (min,max)
结果:
input N time algorithm 1 | time algorithm 2
1000000 | 0.1299650669 | 0.6347620487
2000000 | 0.266600132 | 1.3034451008
3000000 | 0.393116951 | 2.2436430454
4000000 | 0.5371210575 | 2.5098109245
5000000 | 0.6094739437 | 3.4496300221
6000000 | 0.8271648884 | 4.6163318157
7000000 | 1.0598180294 | 4.8950240612
8000000 | 1.053456068 | 5.1900761128
9000000 | 1.1843969822 | 5.6422820091
10000000| 1.361964941 | 6.9290060997
我不明白为什么第一个算法比第二个算法快,因为第一个算法的复杂度为 2(n -1),第二个算法的复杂度为 3n/2 -2,理论上第一个比第二个慢。为什么会发生?