#include <iostream>
using namespace std;
/************************************************************************/
/* 归并排序算法 */
/************************************************************************/
/******************合并函数**************/
template<class T>
void merge(T A[],T B[],T C[],int len1,int len2){
int a=0,b=0,c=0;
while (c<len1+len2)
{
if (A[a]<B[b])
{
C[c]=A[a];
a++;
c++;
}else{
C[c]=B[b];
b++;
c++;
}
if (a==len1)
{
while (b<len2)
{
C[c]=B[b];
b++;
c++;
}
}
if (b==len2)
{
while (a<len1)
{
C[c]=A[a];
a++;
c++;
}
}
}
}
/******************归并排序******************/
template<class T>
void mySort(T str[],int n){
if (n>1)
{
int len1=n/2;
int len2=n-n/2;
T *str1=new int[len1];
T *str2=new int[len2];
for (int i=0;i<len1;i++)
{
str1[i]=str[i];
}
for (int j=0;j<len2;j++)
{
str2[j]=str[j+len1];
}
mySort(str1,len1);
mySort(str2,len2);
merge(str1,str2,str,len1,len2);
delete []str1;
delete []str2;
}
}
void main()
{
int str[]={1,4,3,2,6,5};
mySort(str,6);
for (int i=0;i<6;i++)
{
cout<<str[i]<<" ";
}
cout<<endl;
}
排序算法之归并排序
最新推荐文章于 2023-09-03 20:36:33 发布