Lesson One of MIT 《Introduction to Algorithms》

文章目录

1.Notes

1.why we study algorithms?
Performance is the foundation of others.
2.asymptotic analysis:
we can drop the lower order terms and ignore leading constants from a formula.

asymptotic notation :theta notation Θ \Theta Θ

worst case.
average case.
best case.

3.insertion sort.
worst case: Θ ( n 2 ) \Theta(n^2) Θ(n2)
average case: Θ ( n 2 ) \Theta(n^2) Θ(n2)
best case: Θ ( n ) \Theta(n) Θ(n)
4.merge sort.
Θ ( n l o g n ) \Theta(nlogn) Θ(nlogn)
5.recursion tree
T ( n ) = 2 ∗ T ( n / 2 ) + n T(n) = 2*T(n/2) + n T(n)=2T(n/2)+n
在这里插入图片描述

2.Code

void insertionSort(vector<int> &v){
	int len =v.size();
	for(int i = 1; i<len; i++){
		for(int j =i-1; j>=0; j--){
			if(v[j] > v[j+1]){
				v[j+1] = v[j+1] + v[j];
				v[j] = v[j+1] - v[j];
				v[j+1] = v[j+1] - v[j];
			}
		}	
	}
}
void mergeSort(vector<int> &v,int lo, int hi){
	//递归基
	if(hi - lo == 1)
		return;
	//分治
	int mid = (lo + hi)/2;
	mergeSort(v, lo, mid);
	mergeSort(v, mid , hi);
	//合并
	vector<int> vv;
	for(int i=0; i<mid ; i++){
		vv.push_back(v[lo+i]);
	}
	int lb = mid - lo;
	int lc = hi - mid;
	for(int i=0,j=0,k=0; j<lb||k<lc;){
		if(j<lb && (vv[j]<=v[mid+k]||k>=lc)) {v[lo+i]=vv[j]; j++; i++;}
		if(k<lc && (vv[j]>v[mid+k]||j>=lb)) {v[lo+i]=v[mid+k]; k++; i++;}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值