关于数据结构:归并排序递归

41次阅读

共计 916 个字符,预计需要花费 3 分钟才能阅读完成。

#include <iostream>
using namespace std;
#define  MAXSIZE  20                              
typedef struct{
    int key;
    char *otherinfo;
}RedType;
typedef struct{
    RedType *r;
    int length;
}SqList;                                                                        
void Create_Sq(SqList &L){
    int i,n;
    cout<<"数据个数:";
    cin>>n;                                        
    cout<<"待排序的数据:";
    for(i=1;i<=n;i++){cin>>L.r[i].key;
        L.length++;
    }
}
// 相邻两个有序子序列归并
void Merge(RedType R[],RedType T[],int low,int mid,int high){ 
    int i,j,k;
    i=low; j=mid+1;k=low; 
    while(i<=mid&&j<=high){if(R[i].key<=R[j].key) T[k++]=R[i++]; 
        else T[k++]=R[j++]; 
    } 
    while(i<=mid)                                    
        T[k++]=R[i++];                 
    while(j<=high)                               
        T[k++]=R[j++];                       
}
void MSort(RedType R[],RedType T[],int low,int high){ 
    int mid;
    RedType *S=new RedType[MAXSIZE];
    if(low==high) T[low]=R[low]; 
    else{mid=(low+high)/2;                       
        MSort(R,S,low,mid);                            
        MSort(R,S,mid+1,high);                        
        Merge(S,T,low,mid,high);                    
    }
}
// 归并排序 
void MergeSort(SqList &L){MSort(L.r,L.r,1,L.length); 
}
void show(SqList L){
    int i;
    for(i=1;i<=L.length;i++)
        cout<<L.r[i].key<<" ";
}
int main(){
    SqList R;
    R.r=new RedType[MAXSIZE+1];
    R.length=0;
    Create_Sq(R);
    MergeSort(R);
    cout<<"归并排序:";
    show(R);
}

正文完
 0