全部博文(136)
分类: C/C++
2011-03-15 09:27:22
O-notation's basic parameter is n, the size of a problem instance, and the complexity or running time is expressed as a function of n. The ``O'' is for order, as in ``Binary search is O(log n); it takes on the order of logn steps to search an array of n items.''
The notation O(f(n)) means that, once n gets large, the running time is proportional to at most f(n), for example, O(n2) or O(nlog n).
Asymptotic estimates like this are valuable for theoretical analyses and very helpful for gross comparisons of algorithms, but details may make a difference in practice.
We must also distinguish between worst-case and expected behavior. It's hard to define ``expected,'' since it depends on assumptions about what kinds of inputs will be given.
Quicksort's worst-case run-time is O(n2) but the expected time is O(n log n). By choosing the pivot element carefully each time, we can reduce the probability of quadratic or O(n2) behavior to essentially zero; in practice, a well-implemented quicksort usually runs in O(n log n) time.
Notation | Name | Example |
---|---|---|
O(1) | constant | array index |
O(log n) | logarithmic | binary search |
O(n) | linear | string comparison |
O(nlog n) | nlogn | quicksort |
O(n2) | quadratic | simple sorting methods |
O(n3) | cubic | matrix multiplication |
O(2n) | exponential | set partitioning |