归并排序

来源:互联网 发布:淘宝一口价设置技巧 编辑:程序博客网 时间:2024/06/08 07:55
稳定排序(可用于链式结构,不需要附加存储空间,递归实现时需要开辟递归工作栈)
#include<iostream>using namespace std;void merge(int a[],int low,int mid,int high){   int i=low,j=mid+1,*temp=new int[high-low+1],k=0;   if(!temp)   {    cout<<"数组分配失败 ";    exit(0);   }    while(i<=mid&&j<=high)      //将a[]中数据有小到大地并入temp[]   {   if(a[i]<=a[j])   temp[k++]=a[i++];   else   temp[k++]=a[j++];   }    while(i<=mid)                //将剩余的a[i]放入temp[]   temp[k++]=a[i++];   while(j<=high)               //将剩余的a[j]放入temp[]   temp[k++]=a[j++];    for(i=low,k=0;i<=high;i++,k++)//将排好序的复制至数组a[]中   a[i]=temp[k];    delete []temp;}void mergesort(int a[],int low,int high){   int mid=(low+high)/2;   if(low<high)  {   mergesort(a,low,mid);        //递归排序   mergesort(a,mid+1,high);     //递归排序   merge(a,low,mid,high);       //合并  }}int main(){  int a[7]={49,38,65,97,76,13,27};  mergesort(a,0,6);  for(int i=0;i<7;i++)  cout<<a[i]<<" ";}


原创粉丝点击