(If you want to be a good programmer,you just programmer every day for two years,you will be an excellent programmer;If you want to be a world-class programmer,you can programmer every day for ten years,or you can program every day for two years and take an algorithms class.)
First day:
performance and resource usage
(user-friendliness,security,feasible,simplicity,maintainablity, cost,stability)
1)sorting:
Insertion sort:(缩进法表示)
for j 2 to n
temp=a[j];
i=j-1
while(i>0 and a[i]>temp)
a[i+1]=a[i];
i--;
a[i+1]=temp;
running time: input status, input size;
kinds of analysis:max,min,average
Asymptotic analysis渐进分析(notation 符号)
舍弃低阶项及常系数
1+2+3+...=O(n^2);
时间复杂度分情况,正向有序时为O(n),反向有序时为O(n^2),稳定;
merge sort: A[1…n]
1.if n=1,done;
2.分别排序A[1..n/2]和A[n/2+1...n];
3.merge
Key subroutine:merge
对两个分表遍历归并;
Recursion tree递归树 O(n lgn)
void Merge(int a[],int low,int mid,int high){
Int []temp=new int[high-low+1];
Int i=low,j=mid+1;
Int k=0;
While(i<=mid && j<
high-1){
If(a[i]<
a[j]){
Temp[k++]=a[i++];
}else{
Temp[k++]=a[j++];
}
}
While(i<=mid)
Temp[k++]=a[i++];
While(j<=high-1)
Temp[k++]=a[j++];
For(int k2=0;k2<
temp.length;k2++){
A[k2]=temp[k2];
}
}
Int [] MergeSort(int a[],int low,int high){
Int mid=(high-low+1)/2;
While(low<
high){ //递归(mid值不断向low和high靠拢)
MergeSort(a,low,mid); //合并左边
MergeSort(a,mid+1,high); //合并右边
Merge(a,low,high); //左右2路归并
}
Return a;
}
归并排序是一种稳定的排序,时间复杂度O(nlgn),辅助空间复杂度为O(n);