打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
合并排序

#include<iostream>
# include<cstdlib>
# include <conio.h>  
using namespace std;
template<class type>
void merge(type c[],type d[],int l,int m,int r)
{
   int i,j,k;
       k=i=l;
       j=m+1;
   while((i<=m)&&(j<=r))
   { if(c[i]<=c[j])
      d[k++]=c[i++];
    else
     d[k++]=c[j++];
     }
    if(i>m) for(int q=j;q<=r;q++)
    d[k++]=c[q];
    else
    for(int q=i;q<=m;q++)
    d[k++]=c[q];  
   };
template<class type>
void Mergersort(type a[],int left,int right,int n)
{
int i=0;
type *b=new type[n];
if(left<right){
    i=(left+right)/2;
    Mergersort(a,left,i,n);
    Mergersort(a,i+1,right,n);
    merge(a,b,left,i,right);
    for(i=left;i<=right;i++)a[i]=b[i];  
}
}
int main()
{
    int n=0,i=0,p=0,r=0;    
    cout<<"要排序的数的规模"<<endl;
    cin>>n;
    int *a=new int[n];
    cout<<"输入要排序的数:"<<endl;    
    for(i=0;i<n;i++)cin>>a[i];
    p=0;r=n-1;        
    Mergersort(a,p,r,n);   
    cout<<"输出排好的数:"<<endl;
    for(i=0;i<n;i++)cout<<a[i]<<' ';
    cout<<endl;   
    getch();
    return 0;
}

#include<iostream>
# include<cstdlib>
# include <conio.h>  
using namespace std;
template<class type>
void merge(type c[],type d[],int l,int m,int r)
{
   int i,j,k;
       k=i=l;
       j=m+1;
   while((i<=m)&&(j<=r))
   { if(c[i]<=c[j])
      d[k++]=c[i++];
    else
     d[k++]=c[j++];
     }
    if(i>m) for(int q=j;q<=r;q++)
    d[k++]=c[q];
    else
    for(int q=i;q<=m;q++)
    d[k++]=c[q];  
   };
template<class type>
void Mergersort(type a[],int left,int right,int n)
{
int i=0;
type *b=new type[n];
if(left<right){
    i=(left+right)/2;
    Mergersort(a,left,i,n);
    Mergersort(a,i+1,right,n);
    merge(a,b,left,i,right);
    for(i=left;i<=right;i++)a[i]=b[i];  
}
}
int main()
{
    int n=0,i=0,p=0,r=0;    
    cout<<"要排序的数的规模"<<endl;
    cin>>n;
    int *a=new int[n];
    cout<<"输入要排序的数:"<<endl;    
    for(i=0;i<n;i++)cin>>a[i];
    p=0;r=n-1;        
    Mergersort(a,p,r,n);   
    cout<<"输出排好的数:"<<endl;
    for(i=0;i<n;i++)cout<<a[i]<<' ';
    cout<<endl;   
    getch();
    return 0;
}

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
各种排序算法C++实现(冒泡,选择,插入,快速,归并,堆)
类的特化
用线性表实现多项式的加法和乘法
C++函数模板
c++中using的用法
几种C++排序算法的实现(冒泡,归并,快速,插入,选择)
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服