# 归并排序

#include <iostream>
#include <vector>

using namespace std;

void Show(vector<int> & vec)
{
vector<int> :: iterator   it = vec.begin();
for(it;it != vec.end();it++)
{
cout<<*it<<"  ";
}
cout<<endl;
}

void Merge(vector<int> & vec,int width,int len)//时间复杂度O(n)  空间复杂度O(1)  稳定
{
int low1 = 0;
int high1  = low1 + width -1;
int low2 = high1 + 1;
int high2 = low2 + width -1 < len? low2 + width -1:len -1;
vector<int>  vec_tmp;
//有两个两个数据段

while(low2 <= high2)
{
//两个数据段上此时都有数据，
while(low1 <= high1 && low2 <= high2)
{
if(vec[low1] <= vec[low2])
{
vec_tmp.push_back(vec[low1++]);
}
else
{
vec_tmp.push_back(vec[low2++]);
}
}

//将数据段上剩余数据，拷贝到临时变量中。
while(low1 <= high1)
{
vec_tmp.push_back(vec[low1++]);
}
while(low2 <= high2)
{
vec_tmp.push_back(vec[low2++]);
}

low1 = high2 + 1;
high1  = low1 + width -1;
low2 = high1 + 1;
high2 = low2 + width -1 < len? low2 + width -1:len -1;
}

//当分配的是，奇数个组数时，会有一个数组的数据没有处理
while(low1 < len)
{
vec_tmp.push_back(vec[low1++]);
}

for(int i = 0; i < len ;++i)
{
vec[i] = vec_tmp[i];
}
}

void  MergeSort(vector<int> & vec)//时间复杂度O(nlogn)  空间复杂度O(n)  稳定
{
int len = vec.size();
if(len <2) return ;
for(int i = 1;i < len;i *= 2)//logn
{
Merge(vec,i,len);
}
}

int main()
{
int arr[10] = {10,9,8,7,6,4,5,2,1,3};
vector<int>  vec(arr,arr+10);
Show(vec);
MergeSort(vec);
Show(vec);
}

11-15
09-11

01-20
05-30 8万+
04-13
03-30
05-03