计算算法
对于这个问题仍然没有结论,所以有穷性得不到保证
程序 不等于 算法 比如死循环或者栈溢出
计算优劣
统一尺度
计算模型(图灵机)
计算模型 (RAM)
渐进分析(大O记号)
分别对应最好和平均情况
渐进分析(多项式)
不含转向(循环 递归 调用),必顺序执行即O(1),反之则不是。
渐进分析(复杂度层级)
算法分析 (级数)
算法分析(迭代)
算法分析(正确性)
算法分析(封底估算)
相比于硬件,算法的改进更为重要
迭代与递归(减而治之)
else 隐含了两种递归基
迭代与递归(分而治之)
迭代与递归(Max2)
x1 指向最大值
x2 指向次大值
有两个递归基 分别对应还有两个和三个的情况,由于是左闭右开所以是+2和+3
#include <stdio.h>
#include <string.h>
void max2(int A[], int lo, int hi, int& x1, int& x2){//注意引用
if(lo + 2 == hi){//递归基 两个数
x1 = (A[lo] > A[hi - 1]) ? lo : hi - 1;//x1 最大值
x2 = (A[hi - 1] <= A[lo]) ? hi - 1 : lo;//x2 次大值
return; //返回语句不要忘
}
if(lo + 3 == hi){//递归基 三个数时
if(A[hi - 1] > A[hi - 2] && A[hi - 1] > A[lo]){//分三种情况讨论
x1 = hi - 1;
x2 = (A[hi - 2] > A[lo]) ? hi - 2 : lo;
}else if(A[hi - 2] > A[hi - 1] && A[hi - 2] > A[lo]){
x1 = hi - 2;
x2 = (A[hi - 1] > A[lo]) ? hi - 1 : lo;
}else {
x1 = lo;
x2 = (A[hi - 1] > A[hi - 2]) ? hi - 1 : hi -2;
}
return;
}
int mi = (lo + hi) / 2;//二分
int x1L,x2L;//定义左半部分的最大值和次大值
max2(A, lo, mi, x1L, x2L);//递归求出最大值和次大值
int x1R,x2R;//定义右半部分的最大值和次大值
max2(A, mi, hi, x1R, x2R);//递归求出最大值和次大值
if(A[x1L] > A[x1R]){//左半部分的最大值更大
x1 = x1L;
x2 = (A[x2L] > A[x1R]) ? x2L : x1R;//次大值只能在左半部分的次大值和右半部分的最大值中产生
} else {//右半部分的最大值更大
x1 = x1R;
x2 = (A[x1L] > A[x2R]) ? x1L : x2R;//次大值只能在右半部分的次大值和左半部分的最大值中产生
}
}
int main(){
int A[] = {3, 2, 5, 46, 23, 15};
int x1 = 0;
int x2 = 0;
int len = sizeof(A) / sizeof(int); //整数数组 不能用strlen函数求
// printf("%d",len);
max2(A, 0, len, x1, x2);
printf("%d %d",A[x1], A[x2]);
return 0;
}
Python没有引用 故函数要返回x1和x2(by wangyanhong11)
shu = [3, 2, 5, 98, 46, 23, 15]
def max2(shu, lo, hi, x1, x2):
if(lo + 2 == hi):
x1 = (shu[lo] if(shu[lo] > shu[hi - 1]) else shu[hi - 1])
x2 = (shu[hi - 1] if(shu[hi - 1] <= shu[lo]) else shu[lo])
# print(x1,x2)
elif(lo + 3 == hi):
mi = (lo + hi) // 2
if shu[lo] > shu[mi] and shu[lo] > shu[hi - 1]:
x1 = shu[lo]
x2 = (shu[mi] if(shu[mi] > shu[hi - 1]) else shu[hi - 1])
# print(x1,x2)
elif shu[mi] > shu[lo] and shu[mi] > shu[hi - 1]:
x1 = shu[mi]
x2 = (shu[lo] if(shu[lo] > shu[hi - 1]) else shu[hi - 1])
# print(x1,x2)
else:
x1 = shu[hi - 1]
x2 = (shu[lo] if(shu[lo] > shu[mi]) else shu[mi])
# print(x1, x2)
else:
mid = (lo + hi) // 2
x1l = 0
x2l = 0
x1r = 0
x2r = 0
x1l, x2l = max2(shu, lo, mid, x1l, x2l)
print("Right is running")
x1r, x2r = max2(shu, mid, hi, x1r, x2r)
print("Right is over")
if(x1l > x1r):
x1 = x1l
x2 = (x2l if(x2l > x1r) else x1r)
else:
x1 = x1r
x2 = (x1l if(x1l > x2r) else x2r)
# print(x1, x2)
#print(x1, x2)
return x1, x2
x1, x2 = max2(shu, 0, len(shu), 0, 0)
print(x1, x2)
迭代与递归(尾递归)
尾递归可以转化为相应的迭代版本
动态规划(记忆法)
动态规划(最长公共子序列)