Click here to Skip to main content
15,884,472 members
Please Sign up or sign in to vote.
5.00/5 (2 votes)
See more:
Hello guys,

I decided to try and do a problem about analyzing the worst possible runtime of an algorithm.
Since I'm a beginner and I want to do an understand this right I require some help.

I came accros this problem in a book that uses the following algorithm:

Input: A set of n points (x1, y1), . . . , (xn, yn) with n ≥ 2.
Output: The squared distance of a closest pair of points.
ClosePoints
1. if n = 2 then return (x1 − x2)^2 + (y1 − y2)^2
2. else
3. d ← 0
4. for i ← 1 to n − 1 do
5.....for j ← i + 1 to n do
6. .....t ← (xi − xj)^2 + (yi − yj)^2
7. ......if t < d then
8. .........d ← t
9. return d

These are the questions:
T(n) represents the worst possible runtime.
1. Prove that T(n) = O(n^2). For this part you must use the O(·) notation along with any
appropriate properties .
2. Prove that T(n) = Ω(n^2). (In fact the runtime of the algorithm is Ω(n^2) for all inputs of n
points.)
3. Is it true to say that T (n) = Θ(n^2)? Justify your answer very briefly.

Now 3 is dependent of 1 and 2.As for 1 I know that we say that f is O(g), pronounced
if and only if there is an n0 ∈ N and c > 0 in R such that for all
n ≥ n0 we have
f(n) ≤ cg(n).
And also we say that f is Ω(g) if there is an
n0 ∈ N and c > 0 in R such that for all n ≥ n0 we have
f(n) ≥ cg(n).

I was thinking of either using small positive constants c1, c2, c3, c4.... to represent the cost of executing line 1,2,3,4,.. or maybe just directly O(1)+O(1)+...instead of constants....

How should I solve the questions?
Thanks in advance
Posted
Updated 21-Feb-11 21:59pm
v2
Comments
AkilMai 23-Feb-11 14:07pm    
how can I find a constant to prove 2?

You're doing C * n(n - 1) iterations (where C is some constant), yielding T(n)=C*n^2 - C*n.

Remember that for the O notation we drop constant factors and lower order terms giving O(n)=n^2.

Because you're dropping constant factors I don't think it makes any sense to represent the 1, 2, 3 and 4 as O(1). They just disappear anyway in the asymptotic notation.


Hope this helps,
Fredrik Bornander
 
Share this answer
 
To begin with, you should take a look how many steps the algorithm has to take to end.

For n = 2 this would be 1, as it terminates on line 1.

For n > 2 the number of steps is determined by the two nested loops and be equal to the number of times the outer loop is executed times the number of times the inner loop is executed. So this would be (n - 1) * n.

These are the best and at the same time the worst cases, as this does not change for any n > 1

Especially for n > 2 you probably can easily see the realation to O(n^2) by now.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900