归并排序(合并排序)-递归与分治

1:代码部分:

#include 
using namespace std;
const int MAX = 100;
void Merge(int a[], int left, int mid, int right)
{
    int t_pos = 0, low = left, high = mid + 1;
    int lenth = right - left + 1;
    int temp[lenth];
    while(low <= mid && high <= right)
    {
        if(a[low] < a[high])
        {
            temp[t_pos++] = a[low++];
        }
        else
        {
            temp[t_pos++] = a[high++];
        }
    }
    while(low <= mid)
    {
        temp[t_pos++] = a[low++];
    }
    while(high <= right)
    {
        temp[t_pos++] = a[high++];
    }
    for(int i = 0; i < lenth; ++i)
    {
        a[left++] = temp[i];
    }
}
void MergeSort(int a[], int left, int right)
{
    if(left >= right)
        return;
    else
    {
        int mid = (left + right) / 2;
        MergeSort(a, left, mid);
        MergeSort(a, mid + 1, right);
        Merge(a, left, mid, right);
    }
}
int main()
{
    int a[MAX];
    int num;
    scanf("%d", &num);
    for(int i = 0; i < num; ++i)
    {
        scanf("%d", &a[i]);
    }
    MergeSort(a, 0, num - 1);
     for(int i = 0; i < num; ++i)
    {
        printf("%d ", a[i]);
    }
}

2:时间复杂度分析

 T(n) = O(1)                                  n <= 1;

        = 2 T(n / 2) + O(n)               n > 1;

你可能感兴趣的:(算法设计与分析,计算机算法设计与分析)