MergeSort is the first deterministic sort algorithm whose time conplexity is 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25template <typename T>
void vector<T>::MergeSort(Rank lo,Rank hi)
{
if(hi-lo<2) return;
int mi=(lo+hi)/2;
MergeSort(lo,mi);
Mergesor(mi,hi);
merge(lo,mi,hi);
}
template <typename T>
void vector<T>::merge(Ran lo,Rank mi,Rank hi)
{
T*A=_elem+lo;
int lb=mi-lo;
T* B=new T[lb];
for(Rank i=0;i<lb;B[i]=A[i++];) ; //复制前子向量[WHY?]
int lc=hi-mi;
T* C=_elem+mi; //[WHY?]
for(Rank i=0,j=0,k=0;(j<lb||k<lc);)
{
if((j<lb)&&(!(k<lc)||(B[j]<=C[k]))) A[i++]=B[j++];
if((k<lc)&&(!(j<lb)||(C[k]<B[j]))) A[i++]=C[k++];
}
delete [] B;
}
Complexity Analysis
Easily find that
So, if
Hence,
Then we let
Therefore,