这是我的第一篇博文,学习C++半学期以来,时常会忘记很多基础语法等,经过思考,我决定以后把自己学到的东西都记录下来。一来,帮助记忆;二来,能检查自己是否真的懂了;三来,和广大网友交流分享,这样自己理解有误的地方还能得到改正,实在是利处多多。
算法是程序设计中重要的一环,曾看到有人说:程序=算法+数据结构。可见算法和数据结构的重要性。学习C++半学期,听到最多关于算法的就是算法的复杂度,经常会听到
O(n), O(1), O(n²), O(logn), 指数增长......
初听起来似乎很复杂,今天看书,由于书上并没有多讲,所以目前看来还不是很复杂,不过分析具体的程序的算法复杂度还是挺麻烦的,因为有很多常数次基本操作都需要计入,最终仅保留最高次。
算法的复杂度包括时间复杂度和空间复杂度。
时间复杂度(time complexity):
时间复杂度是对程序运行时间的估计,由于一般情况下,程序运行时间会随着输入规模的增大而增大,所以对时间复杂度的估计依赖于输入规模n,一般,n越大,所消耗的时间就越长,因此,时间复杂度可看作是一个关于n的函数映射,我们记为T(n).
T(n)描述一个程序的计算效率的高低,不同的规模的输入适应不同的算法,并不是说T(n)最小就是最合适的。
D。Knuth在The Art of Computer Programming中提出几种记法,对时间复杂度的分析似乎很重要,也就是O(Big-O notation),Ω(Big-omega notation), Θ(Big-theta notation)
在时间复杂度的分析中,几种常数次基本操作很重要,最终就是通过对他们的次数求和来估算运行时间的。包括:逻辑判断,位运算,加法,右移等
O(n)是对时间复杂度的一个保守估计,也就是T(n)的上界
定义:当存在常数C,使得对任意n>2,均有T(n)≤Cf(n), 则记T(n)=O(f(n))
Ω(n)是对时间复杂度的一个良好估计,也就是T(n)的下界
定义:当存在常数C,使得对任意n>2,均有T(n)≥Cf(n), 则记T(n)=Ω(f(n))
Θ(n)是T(n)的一个类似极限的概念
int count_1s(unsigned int n){
int ones=0;
while(n>0){
ones +=(1 & n);
n >>=1;
}
}