二路歸并遞歸實(shí)現(xiàn)
#include <iostream>
using namespace std;
//參數(shù):r表示待排序數(shù)組,s為r中第一個(gè)有序表的第一個(gè)下標(biāo),m為第一個(gè)有序表的最后一個(gè)下標(biāo);s是r中的最后一個(gè)下標(biāo)
void merge( int r[],int s,int m,int t)
{
int tempr[50];
for(int k = s; k <= t; k++ )
tempr[k] = r[k];
int s1 = s;
int s2 = m+1;
int rs = s;
while(s1 <= m && s2 <= t)
if(tempr[s1]<=tempr[s2])
r[rs++] = tempr[s1++];
else
r[rs++] = tempr[s2++];
while(s1 <= m)
r[rs++] = tempr[s1++];
while(s2 <= t)
r[rs++] = tempr[s2++];
}
void MSort(int r[],int s,int t)
{
int m;
if(s==t)
;
else
{
m = (s+t)/2;
MSort(r,s,m);
MSort(r,m+1,t);
merge(r,s,m,t);
}
}
int main()
{
int r[11] = {34,45,56,2,4,6,12,3,4567,78,11};
MSort(r,0,10);
for(int i=0;i<11;i++)
cout<<r[i]<<endl;
getchar();
return 0;
}
using namespace std;
//參數(shù):r表示待排序數(shù)組,s為r中第一個(gè)有序表的第一個(gè)下標(biāo),m為第一個(gè)有序表的最后一個(gè)下標(biāo);s是r中的最后一個(gè)下標(biāo)
void merge( int r[],int s,int m,int t)
{
int tempr[50];
for(int k = s; k <= t; k++ )
tempr[k] = r[k];
int s1 = s;
int s2 = m+1;
int rs = s;
while(s1 <= m && s2 <= t)
if(tempr[s1]<=tempr[s2])
r[rs++] = tempr[s1++];
else
r[rs++] = tempr[s2++];
while(s1 <= m)
r[rs++] = tempr[s1++];
while(s2 <= t)
r[rs++] = tempr[s2++];
}
void MSort(int r[],int s,int t)
{
int m;
if(s==t)
;
else
{
m = (s+t)/2;
MSort(r,s,m);
MSort(r,m+1,t);
merge(r,s,m,t);
}
}
int main()
{
int r[11] = {34,45,56,2,4,6,12,3,4567,78,11};
MSort(r,0,10);
for(int i=0;i<11;i++)
cout<<r[i]<<endl;
getchar();
return 0;
}
posted on 2011-10-25 10:43 chxzwj 閱讀(348) 評(píng)論(0) 編輯 收藏 引用 所屬分類(lèi): 常用算法