1. 程式人生 > >為面試做準備之歸併排序

為面試做準備之歸併排序

#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;
}