Chinaunix首页 | 论坛 | 博客
  • 博客访问: 222492
  • 博文数量: 136
  • 博客积分: 2919
  • 博客等级: 少校
  • 技术积分: 1299
  • 用 户 组: 普通用户
  • 注册时间: 2011-03-11 09:08
文章分类

全部博文(136)

文章存档

2013年(1)

2011年(135)

我的朋友

分类: C/C++

2011-03-15 09:27:22

2.5 O-Notation

2011-03-14 Mon

  • We need a way to make such statements more precise, while at the same time abstracting away details like the CPU speed and the quality of the compiler.
  • We want to compare running times and space requirements of algorithms independently of programming language, compiler, machine architecture, processor speed, system load, and other complicating factors.

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.

O-Notation
NotationNameExample
O(1)constantarray index
O(log n)logarithmicbinary search
O(n)linearstring comparison
O(nlog n)nlognquicksort
O(n2)quadraticsimple sorting methods
O(n3)cubicmatrix multiplication
O(2n)exponentialset partitioning
  • Accessing an item in an array is a constant-time or O(1) operations.
  • An algorithm that eliminates half the input at each stage, like binary search, will generally take O(long n).
  • Comparing two n-character strings with strcmp is O(n).
  • The traditional matrix multiplication algorithm takes O(n3), since each element of the output is the result of multiplying n pairs and adding them up, and there are n2 elements in each matrix.
  • Exponential-time algorithms are often the result of evaluating all possibilities: there are 2n subsets of a set of n items, so an algorithm that requires looking at all subsets will be exponential or O(2n).

阅读(468) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~