Personal understanding of merge sort algorithm implementation

Personal understanding of recursive implementation of merge sort algorithm


Two implementation schemes, recursive and non-recursive (implemented in C++)


First, let's introduce the basic idea of ​​merge sort implementation
1. Divide the array array[n] in half, and proceed in turn until n/2 sub-arrays are obtained 2. Sort
these n/2
arrays in turn 3. Continue to process the array Divide to get n/4 arrays. Since the previous n/2 subarrays have been sorted, the above n /2 arrays are actually merged into sorted n/4 arrays, and sorted, and so on. The resulting n/n (ie 1) arrays are sorted arrays


The code is implemented as follows:
First, the function that merges and sorts subarrays is introduced

void mergearray(int a[], int first, int mid, int last, int temp[])  
{  
    int i = first, j = mid + 1;  
    int m = mid,   n = last;  
    int k = 0;  

//比较两个子数组中的元素
    while (i <= m && j <= n)  
    {  
        if (a[i] <= a[j])  
            temp[k++] = a[i++];  
        else  
            temp[k++] = a[j++];  
    }  
//将剩下的元素赋值给temp
    while (j <= n)  
        temp[k++] = a[j++];  

    while (i <= m)  
        temp[k++] = a[i++];  
//将排序成功的temp数组里面的值赋值给原数组
    for (i = 0; i < k; i++)  
        a[first + i] = temp[i];  
}  

sort recursively

void MergeSort(int a[], int first, int last, int temp[])  
{  
    if (first < last)  
    {  
        int mid = (first + last) / 2;  
        mergesort(a, first, mid, temp);    //左边有序  
        mergesort(a, mid + 1, last, temp); //右边有序  
        mergearray(a, first, mid, last, temp); //再将二个有序数列合并  
    }  
}  

non-recursive implementation

void MergeSort(int a[],int n){
    int* temp = new int(n);
    int size = 1,first,mid;//size为每次子数组的大小/2 
    while(size<n){
        first=0;
        while(first+size<n){
            mid = first+size-1;//得到每次要归并的数组的中间下标
            //归并数组的最后一个下标若超过数组大小则按n-1处理
            mergesort(a,first,mid+size>n-1?n-1:mid+size,temp);
            cout<<"first:"<<first<<" mid:"<<mid<<" last:"<<(mid+size>n-1?n-1:mid+size)<<endl;//打印出每次归并的区间   
            first = mid+size+1;
        }
        size*=2;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325484964&siteId=291194637