merge_sort2 do not use the sentinels (recursive)

时间:2021-12-28 18:23:56
//algo/merge_sort2.cpp
//do not use the sentinels

#include <iostream>
using namespace std;

//#define LOG_OUT

void merge(int list[],int p,int q,int r)
{
    //merge the sorted list, list[p,q],list[q+1,r] to one sorted list, list[p,r]
    int n1 = q-p+1;
    int n2 = r-q;
   
    int i,j;
   
    int *L = new int[n1];
    int *R = new int[n2];
   
    if(L==NULL || R==NULL)
        cerr<<"memory new error!"<<endl;
   
    //assignment
#ifdef LOG_OUT
    cout<<"Array L: "<<endl;
#endif
    for(i=0;i<n1;++i){
        L[i] = list[p+i];
#ifdef LOG_OUT
        cout<<"L["<<i<<"] = "<<L[i]<<" ";
#endif
    }
#ifdef LOG_OUT
    cout<<endl;
    cout<<"Array R: "<<endl;
#endif
    for(j=0;j<n2;++j){
        R[j] = list[q+1+j];
#ifdef LOG_OUT
        cout<<"R["<<j<<"] = "<<R[j]<<" ";
#endif
    }
#ifdef LOG_OUT
    cout<<endl;
#endif
   
    i=0;j=0;
   
    for(int k=p;k<=r;++k){
        if(i==n1){
            for(;j<n2;++j){
                list[k++] = R[j];
            }
            break;
        }
        if(j==n2){
            for(;i<n1;++i){
                list[k++] = L[i];
            }
            break;
        }
        if(L[i]<=R[j]){
            list[k] = L[i++];
        }
        else{
            list[k] = R[j++];
        }
    }   
   
    //if not use delete, will memory leak
    delete []L;
    delete []R;
}

void merge_sort(int list[],int p,int r)
{
    int sz= r-p+1;
    if(sz>1){
        int q = (p+r)/2;
        merge_sort(list,p,q);
        merge_sort(list,q+1,r);
        merge(list,p,q,r);
    }
}

int main()
{
    int list[] = {7,4,5,8,9,1,3,5,6,8};
    //int list[] = {3,41,52,26,38,57,9,49};
   
    for(int i=0;i<10;++i){
        cout<<list[i]<<" ";
    }
    cout<<endl;
   
    merge_sort(list,0,9);
   
    for(int i=0;i<10;++i){
        cout<<list[i]<<" ";
    }
    cout<<endl;
   
    return 0;
}