ACM - 归并排序

这篇博客主要介绍了ACM中的归并排序算法。文章通过程序展示、效果演示和算法复杂度分析,详细解释了归并排序的过程。算法复杂度分析部分提到,归并排序采用递归方式,共有1+logN层,每层时间代价为cn,因此总复杂度为NlogN。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

程序

/** 
  *@descript :   归并排序
  *@author   :   chenzx
  *@copyright:   2012-12-3(c++)
  */

#include <iostream>

using namespace std;

const int N = 7;

void print_arry(int * arry, int len){

    for (int i = 0; i < len; i++)
    {
        cout<<arry[i]<<"  ";
    }
    cout<<endl;
}
 
/*  将已序的fist->mid-1, 和mid->last 归并在一起   */ 
void  merge_arry(int arry[], int first, int mid, int last){
    
    int first1 = first,   last1 = mid ;    //定义左有序序列的起始结束位置
    int first2 = mid + 1, last2 = last;    //定义右有序序列的起始结束位置
    int *temp = new int[last - first + 1]; //分配临时保存的空间
    int index = 0;

    //1. 将两个序列归并到临时数组中
    while((first1 <= mid) && (first2 <= last)){

        if (arry[first1] < arry[first2]){
            temp[index++] = arry[first1++];        
        }else{
            temp[index++] = arry[first2++];     
        }
    }
    //2. 将剩余的部分添加到临时数组中
    while(first1 <= mid){
        temp[index++] = arry[first1++];
    }
    while(first2 <= last){
        temp[index++] = arry[first2++];
    }

   // print_arry(temp, last- first + 1);

    //3. 将临时数组中的内容返回给arry
    index = 0;
    for (int i = first; i <= last; i++){
        arry[i] = temp[index++];
    }

    delete[]  temp;
}

/* 使用递推将序列first->last 序列进行归并排序         */
void merge_sort(int * arry, int first, int last){

    int mid = 0;
    if (first < last)
    {
        mid = (first + last)/2;
        merge_sort(arry, first, mid);
        merge_sort(arry, mid + 1, last);
        merge_arry(arry,first, mid, last);
    }
    //print_arry(arry,N);

}

int main()
{
    cout<<"This is merge sort!"<<endl;

    int arry[N] = {3,5,8,1,2,7,4};

    cout<<"The orige number :"<<endl;
    print_arry(arry, N);

    merge_sort(arry, 0, N - 1);

    cout<<"The  sort number :"<<endl;
    print_arry(arry, N);

    system("pause");
    return 0;
}

效果图


算法复杂度分析


1) 归并递归的一般公式


 

2) 如图,在b~d的过程不断的进行二分,所以一共有 logN 层,加上第一层,所以一共有1+logN
3) C表示规模为1的问题所需要的时间,每层的时间代价和总是cn  
4) 所以最终结果就是 cn1 + logN
5) 算法复杂度在NlogN的量级上



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值