当先锋百科网

首页 1 2 3 4 5 6 7

归并排序:

void merge(int *a,int *b ,int left,int right)
{
    int l = left;
    int r = right+1;
    int m = (left+right)/2;
    int k = m+1;
    int i = left;
    while (l<(m+1)&&k<r)
    {
        if (a[l]<a[k])
        {
            b[i] = a[l];
            i++;
            l++;
        }
        else
        {
            b[i] = a[k];
            i++;
            k++;
        }
    }
    if (k>=r)
    {
        while (l<(m+1))
        {
            b[i] = a[l];
            i++;
            l++;
        }
    }
    else
    {
        while (k<r)
        {
            b[i] = a[k];
            i++;
            k++;
        }
    }
    for (int i = left;i<=right;i++)
    {
        a[i] = b[i];
    }
}

void merge_sort(int * a,int * b,int left,int right)
{
    if (left < right)
    {
        int middle = (left+right)/2;
        merge_sort(a,b,left,middle);
        merge_sort(a,b,middle+1,right);
        merge(a,b,left,right);
    }
}


int main()
{
    int a[10] = {9,2,8,3,5,7,6,1,4,10};
    int b[10]={0};
    merge_sort(a,b,0,9);
    for (int i=0;i<10;i++)
    {
        cout<<a[i]<<" ";
    }
    return 0;
}

平均时间复杂度:nlogn

额外空间:n

稳定性:稳定

比较操作的次数介于(nlogn) / 2和nlogn - n + 1