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)=2∗T(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++;}
}
}