归并排序

归并排序:

基本思想:把待排序序列分成相同大小的两个部分,依次对这两部分进行归并排序,完毕之后再按照顺序进行合并。

时间复杂度: O(nlog2n)-->O(nlog2n)

空间复杂度:O(1)

是否稳定排序:稳定

#pragma once

//merge ordered array a[left:i] & array[i + 1:right] to b[0...]
void Merge(int a[], int b[], int left, int i, int right)
{
    int a1_begin = left, a1_end = i;
    int a2_begin = i + 1, a2_end = right;
    int len = right - left + 1;
    int b_start = 0;
    for (int j = 0; j < len; ++j)
    {
        if (a1_begin > a1_end)
        {
            b[b_start++] = a[a2_begin++];
        }
        else if (a2_begin > a2_end)
        {
            b[b_start++] = a[a1_begin++];
        }
        else
        {
            if (a[a1_begin] > a[a2_begin])
            {
                b[b_start++] = a[a2_begin++];
            }
            else
            {
                b[b_start++] = a[a1_begin++];
            }
        }
    }
}

//copy b[] to a[]
void Copy(int a[], int b[], int left, int right)
{
    int len = right - left + 1;
    for (int i = 0; i < len; ++i)
    {
        a[left+i] = b[i];
    }
}

void MergeSort(int array[], int left, int right)
{
    if (left >= right)
    {
        return;
    }

    int *ptr = new int[right - left + 1];
    int mid = (left + right) / 2;
    MergeSort(array, left, mid);
    MergeSort(array, mid + 1, right);
    Merge(array, ptr, left, mid, right);

    Copy(array, ptr, left, right);

    delete[]ptr;
    ptr = NULL;
}

void TestMergeSort()
{
    int array[] = { 777, 555, 4, 4, 4, 3, 3, 445, 555, 33, 66, 22, 566, 88, 55, 44, 66, 33, 55, 2, 7, 9, 0, -1, -99, 4555, 444, 33, 2, 3, 4, 54, 5, 4, 3, 3, 4, 4, 5, 65, 44, 3, 4 };
    int len = sizeof(array) / sizeof(int);
    MergeSort(array, 0, len - 1);

    for (int i = 0; i < len; ++i)
    {
        cout << array[i] << ",";
    }
}

 

posted @ 2016-07-18 20:53  715776681  阅读(135)  评论(0编辑  收藏  举报