sort(S);
for i=0 to n-2 do
a = S[i];
start = i+1;
end = n-1;
while (start < end) do
b = S[start]
c = S[end];
if (a+b+c == 0) then
output a, b, c;
start = start + 1;
end = end - 1;
else if (a+b+c > 0) then
end = end - 1;
else
start = start + 1;
end
end
此处sort(S)对具有时间复杂度O(n ^ 2)的给定整数进行排序。我如何找到上述问题的复杂性。我们需要任何高阶数学来解决这个问题吗?
答案 0 :(得分:1)
通过考虑最坏的情况来简化伪代码。
sort(S); # O(N log(N))
for i=0 to n-2 do # O(N)
start = i+1; # O(1)
end = n-1; # O(1)
while (start < end) # O(N - i)
start = start + 1; # O(1)
end
end
也可以写成:
sort(S);
for i=0 to n-2 do
for j = i+1 to n-1 do:
...
end
end
所以迭代次数是
1/2 N * (N+1) = O(N^2)
是排序功能的主要术语。