I've written a brute force search algorithm for the travelling salesman problem, and tested it to see the time it takes for various numbers of 'cities'. From the graph below, we can see that the time is roughly proportional to (n-1)!
where n
is the number of 'cities'. It is not directly proportional to n!
(after all, (n-1)! = n! / n
).
My question is, is it still correct to say that the algorithm runs in O(n!)
, or is it better for me to say O((n-1)!)
? I've never seen the latter before, but it seems more accurate. It seems that I've misunderstood something here.
[t = time taken, n = number of cities]
Linear Time Complexity: O(n) This means that as the input grows, the algorithm takes proportionally longer to complete. Linear Time Complexity. These are the type of situations where you have to look at every item in a list to accomplish a task (e.g. find the maximum or minimum value).
For the input of size n , an algorithm of O(n) will perform steps perportional to n , while another algorithm of O(log(n)) will perform steps roughly log(n) . Clearly log(n) is smaller than n hence algorithm of complexity O(log(n)) is better. Since it will be much faster.
As we increase the input size 'n', O(1) will outperforms O(log n). Let's see an example, suppose n = 2048, now Code 1 will take 4 ms as it took previously but Code 2 will take 11 ms to execute. In this case, O(1) outperformed O(log n).
Therefore, we would say that the best-case time complexity of insertion sort is O(n). A complexity of O(n) is also often called linear complexity.
By definition, O(f(n)) is the set of all functions that are asymptotically dominated by f(n), i.e. the set of all functions g(n) for which there are constants C and n_0 such that
g(n) < C * f(n) for all n > n_0
From this definition, it follows that O(n!) is actually a superset of O((n-1)!), since the function f(n) = n! is a member of the first set, but not of the second set. The two sets aren't actually the same.
It is correct, though, to say that your problem is O(n!), since this only states an upper boundary. It would not be correct to say that your problem is ϴ(n!), since this denotes the exact asymptotic behaviour up to constant factors.
There is no big difference in practice, and, as noted in another answer, you can redefine n to mean the number of cities minus one.
O(n!)
is good enough. n
or n-1
makes no difference for large n
.
See https://www.wikiwand.com/en/Time_complexity#/Table_of_common_time_complexities for examples.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With