merge sort

归并排序:归并排序(英语:Merge sort,或mergesort),是创建在归并操作上的一种有效的排序算法,效率为O(n log n)。1945年由约翰·冯·诺伊曼首次提出。该算法是采用分治法(Divide and Conquer)的一个非常典型的应用,且各层分治递归可以同时进行。

该算法是采用分治法(Divide and Conquer)的一个非常典型的应用。

归并排序是稳定排序,它也是一种十分高效的排序

 

 

 

void mergeSort ( int array[], int min, int max)
{
    // prerequisite
    if (min < max)
    {
        // get the middle point
        int mid = ( int )floor((max + min) / 2) ;
        // apply merge sort to both parts of this
        mergeSort(array, min, mid) ;
        mergeSort(array, mid + 1, max) ;
        // and finally merge all that sorted stuff
        merge(array, min, max, mid) ;
    }
}
void merge ( int array[], int min, int max, int mid)
{
    int firstIndex = min ;
    int secondIndex = mid + 1 ;
    int index = min ;
    int tempArray[max] ;
    // if there are still objects in both arrays
    while ((firstIndex <= mid) && (secondIndex <= max))
    {
        if (array[firstIndex] < array[secondIndex])
        {
            tempArray[index] = array[firstIndex] ;
            index ++ ;
            firstIndex ++ ;
        }
        else
        {
            tempArray[index] = array[secondIndex] ;
            index ++ ;
            secondIndex ++ ;
        }
    }
    // terminates the object of the lower array
    while (firstIndex <= mid)
    {
        tempArray[index] = array[firstIndex] ;
        index ++ ;
        firstIndex ++ ;
    }
    // terminates the object of the upper array
    while (secondIndex <= max)
    {
        tempArray[index] = array[secondIndex] ;
        index ++ ;
        secondIndex ++ ;
    }
    // transfer to the initial array
    for ( int i = min ; i < index ; i ++ )
        array[i] = tempArray[i] ;
}

 

总的平均时间复杂度为O(nlogn)。而且,归并排序的最好,最坏,平均时间复杂度均为O(nlogn)。

转载于:https://www.cnblogs.com/guxuanqing/p/9351508.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值