C++ 归并排序算法的代码

将开发过程中比较好的代码片段做个备份,下面代码内容是关于C++ 归并排序算法的代码。

#include<iostream.h>
#include<math.h>


void main()
{
 int a[100],b[100],c[200],m,n,s,i;

 char key;

 cout<<"Well come to merge sort program of C++ ."<<endl;

do{

        cout<<endl;
        cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;

	cout<<"How many number do you need for array a?"<< endl;
	cout<<"m=";   cin>>m;

	cout<<"Now please enter m numbers in array a :"<<endl;
	for(i=0;i<m;++i)
	 {
	  cout<<"element["<<(i+1)<<"]=";
	  cin>>a[i];
	 }
	bubblesortAsce(a,m);

	cout<<"a ASCENDING sorted is:"<<endl;
	for(i=0;i<m;++i)
	 {
	  cout<<" "<<a[i]<<" ";
	 }

	cout<<endl;
	cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;

	cout<<"How many number do you need for array b?"<<endl;
	cout<<"n=";   cin>>n;

	cout<<"Now please enter n numbers in array b :"<<endl;
	for(i=0;i<n;++i)
	 {
	  cout<<"element["<<(i+1)<<"]=";
	  cin>>b[i];
	 }

        bubblesortDesce(b,n);

        cout<<"b DESCENDING sorted is:"<<endl;
        for(i=0;i<n;++i)
	 {
	  cout<<" "<<b[i]<<" ";
	 }

        cout<<endl;
        cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;

        cout<<"array c is merged array."<<endl;
        merge(a,b,c,m,n);
        for(i=0;i<m+n;++i)
	{
	 cout<<" "<<c[i]<<" ";
	}

        cout<<endl;
        cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"<<endl;

        cout<<"nnDo you want to continue to work by program?"<<endl;
        cout<<"If you want it press y ,whereas press any key."<<endl;
        cin>>key;
 }
 while(key=='y' || key=='Y');
}


void bubblesortAsce(int x[],int y)
{
int i,j,hold;
for(i=1;i<=y-1;++i)
 for(j=0;j<y-i;++j)
 {
  if(x[j] > x[j+1])
  {
    hold=x[j];
    x[j]=x[j+1];
    x[j+1]=hold;
  }
 }
}



void bubblesortDesce(int z[],int w)
{
 int i,j,hold;

 for(i=1;i<=w-1;++i)
  for(j=0;j<w-i;++j)
  {
    if(z[j] < z[j+1])
    {
      hold=z[j];
      z[j]=z[j+1];
      z[j+1]=hold;
    }
  }
}


void merge(int x[],int z[],int ME[],int y,int w)
{
 int i,j,l,s;
 s=w+y;

 for(i=0,j=w-1,l=0 ; i<y && j>=0 ;     )
  if(x[i]<z[j])
  {
    ME[l]=x[i];
    ++i;
    ++l;
  }

  else
  {
    ME[l]=z[j];
    --j;
    ++l;
  }


 if(y>w)
  for(; i<y;++i,l++)
   ME[l]=x[i];

 else
  for(; j>=0; l++,--j)
   ME[l]=z[j];

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值