zoukankan      html  css  js  c++  java
  • 归并排序

      今天写的是归并排序,废话不多说了,贴上代码。来自于Introduction to Algorithms。

    void MergeSort(int * x, int n){
    M_Sort(x, 0, n - 1);
    }

    void M_Sort(int * x, int left, int right){//the real MergeSort
    int middle = 0;
    if ( right - left == 1){
    if ( x[left] > x[right] )
    Exchange(x[left], x[right]);
    }
    else if ( left != right ){
    middle = ( right + left ) / 2;
    M_Sort(x, left, middle);
    M_Sort(x, middle + 1, right);
    //Merge
    int * temp = new int[right - left + 1];
    int i = left;
    int j = middle + 1;
    int k = 0;
    while ( i <= middle && j <= right ){
    if ( x[i] <= x[j] ){
    temp[k] = x[i];
    i++;
    }
    else{
    temp[k] = x[j];
    j++;
    }
    k++;
    }
    /*若左边的序列都已在正确的位置上,则右边的序列也就在正确的位置上了,不需变化
    若右边的序列都已在正确的位置上,则需要把左边序列中剩余的部分移至序列的最后
    */
    if ( j > right ){
    for ( int t = 0; t <= middle - i; t++ ){
    x[right - t] = x[middle - t];
    }
    }
    //将temp复制回x
    for ( int t = 0; t < k; t++ ){
    x[left + t] = temp[t];
    }
    delete [] temp;
    }
    return;
    }

    void Exchange(int &a, int &b){
    int temp = a;
    a = b;
    b = temp;
    return;
    }

      复杂度:归并两个长度分别为m,n的序列需O(n+m)次比较和移动,在最坏情况下,到底需要几次比较呢,怎样的两个序列是最坏情况。。。大家可以想一想,这里也就不什么都说明白了,思考有助于理解。考虑一个长度为n的序列,采用归并排序需要O(nlogn)的比较和O(nlogn)的数据移动。

      在n较大的情况下,归并排序优于插入排序,但是归并排序有两个缺点:1.不易实现2.需要额外的存储空间。

      P.S:还是希望看过的同学提提意见。。。


  • 相关阅读:
    Spring源码分析(一)
    keras默认配置
    keras中常用的初始化器
    keras手写数字识别
    tensorflow实现XOR
    sklearn PCA的使用
    git常用操作
    Microsoft Visual C++ 14.0 is required问题解决
    TensorFlow2.0提示Cannot find reference 'keras' in __init__.py
    线性回归处理非数值型数据
  • 原文地址:https://www.cnblogs.com/lyp3314/p/2255731.html
Copyright © 2011-2022 走看看