#include <vector>
#include <iostream>
using namespace std;
void Merge(vector<int> &SR, int i,int m,int n)
{
int j,k,t=i;
vector<int> TR;
for(j=m+1,k=t; t<=m && j<=n; ++k)
{
if(SR[t] <= SR[j])
{
TR.push_back(SR[t++]);
}else{
TR.push_back(SR[j++]);
}
}
while(t<=m)
{
TR.push_back(SR[t++]);
}
while(j<=n)
{
TR.push_back(SR[j++]);
}
for(int p=i,q=0; p<=n; p++,q++) //将排好序的数据写回原来位置
{
SR[p] = TR[q];
}
}
void MSort(vector<int> &SR,int s,int t)
{
int m;
if(s < t)
{
m = (s+t)/2;
MSort(SR,s,m);
MSort(SR,m+1,t);
Merge(SR,s,m,t);
}
}
int main()
{
vector<int> A;
A.push_back(1);
A.push_back(3);
A.push_back(5);
A.push_back(7);
A.push_back(9);
A.push_back(2);
A.push_back(4);
A.push_back(6);
A.push_back(8);
A.push_back(10);
vector<int> &refA = A;
MSort(refA,0,9);
for(int i=0;i<10;i++)
{
cout<<A[i]<<" ";
}
cout<<"A长度为:"<<A.size();
return 0;
}
为面试做准备之归并排序
最新推荐文章于 2022-02-27 01:32:00 发布