归并排序基本操作

#include <bits/stdc++.h>
using namespace std;
class Sort
{
public:
    Sort(int a[],int n);
    //两个相邻子序列的合并
    
    void MergeSort(int first,int last);
    void pp()
    {
        for(int i=0;i<length;i++)
        cout<<data[i]<<" ";
    }
private:
    int length;
    int *data;
    void Merge(int first,int last1,int last2);
};
Sort::Sort(int a[],int n)
{
    data=new int [n];
    length=n;
    for(int i=0;i<n;i++)
    data[i]=a[i];
}
void Sort::Merge(int first,int last1,int last2)
{
    int i,j,k;
    int *temp;
    temp=new int [length];
    i=first,j=last1+1,k=first;
    while(i<=last1&&j<=last2)
    {
        if(data[i]<data[j])
        temp[k++]=data[i++];
        else
        {
            temp[k++]=data[j++];
        }
    }
        //对第一个数组收尾
        while(i<=last1)
        {
           temp[k++]=data[i++];
        }
        //对第二个数组收尾
        while(j<=last2)
        {
            temp[k++]=data[j++];
        }
        for(int i=first;i<=last2;i++)
        data[i]=temp[i];
        delete[]temp;
        
   
}
void Sort::MergeSort(int first,int last)
{
    if(first==last) return;
    else
    {
        int mid=(last+first)/2;
        MergeSort(first,mid);
        MergeSort(mid+1,last);
        Merge(first,mid,last);
    }
    
}
int main()
{
    int n,*a;
    cin>>n;
    a=new int[n];
    for(int i=0;i<n;i++)
    cin>>a[i];
   
   Sort s(a,n);
   s.MergeSort(0,n-1);
   s.pp(); 
}
发布了41 篇原创文章 · 获赞 5 · 访问量 2987

猜你喜欢

转载自blog.csdn.net/qq_43573743/article/details/103764522