Merge sort summary

Algorithm features:
1. Stable sorting
2. Can be used in chain structure, and no additional storage space is needed, but the corresponding stack needs to be opened during recursion.
3. Time complexity O(nlogn) space complexity O(n);

#include <iostream>
#include<bits/stdc++.h>
using namespace std;
void Merge(int *c,int *b,int low,int mid,int high){
    
    
    int k=low,t=mid+1,r=low;
    while(r<=mid&&t<=high){
    
    
        if(c[r]<=c[t]) {
    
    
            b[k++]=c[r++];
        }else b[k++]=c[t++];
    }
    if(r>mid) while(t<=high) b[k++]=c[t++];
    if(t>high) while(r<=mid) b[k++]=c[r++];
}

void MSort(int *a,int *b,int low,int high){
    
    
     int c[100];
    if(low==high) b[low]=a[low];
    else{
    
    
    int mid=(low+high)/2;
    MSort(a,c,low,mid);
    MSort(a,c,mid+1,high);
    Merge(c,b,low,mid,high);
    }
}

int main()
{
    
    
    int a[9]={
    
    49,38,65,97,76,13,27,49};
    MSort(a,a,0,7);
    for(int i=0;i<=7;i++)
        cout<<a[i]<<" ";
    //cout << "Hello world!" << endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/changbaishannefu/article/details/111598666