是什么都不是 2017-03-16 14:54 采纳率: 0%
浏览 919

分治法 合并排序 递归 为何我把我MS()中的k=l改成k=0,排序就能实现呢?

为何我把我MS()中的k=l改成k=0,排序就能实现呢?

源代码:

 //
//  main.cpp
//  合并排序
//
//  Created by 阿杰 on 17/3/13.
//  Copyright © 2017年 阿杰. All rights reserved.
//

#include <iostream>
#include <iomanip>
using namespace std;

template <class Type>
void M(Type c[],Type d[],int l,int m,int r)
{
    int i=l,j=m+1,k=l;
    while((i<=m)&&(j<=r))
        if(c[i]<=c[j])d[k++]=c[i++];
        else d[k++]=c[j++];

    if(i>m) for(int q=j;q<=r;q++)d[k++]=c[q];
    else for(int q=i;q<=m;q++)d[k++]=c[q];
   /* int a1cout=l,a1end=m,a2cout=m+1,a2end=r,bcout=0;
    for (int j=0; j<r-l+1; j++) {
        if(a1cout>a1end){d[bcout++]=c[a2cout++];continue;}
        if(a2cout>a2end){d[bcout++]=c[a1cout++];continue;}
        if(c[a1cout]<c[a2cout]){d[bcout++]=c[a1cout++];continue;}
        else{d[bcout++]=c[a2cout++];continue;}
    }*/
}
template <class Type>
void C(Type a[],Type b[],int l,int r)
{
    int size=r-l+1;
    for(int i=0;i<size;i++)
        a[l++]=b[i];
}

template <class Type>
void MS(Type a[],int left,int right)
{
    Type *b=new int[right-left+1];
    if(left<right){
        int i=(left+right)/2;
        MS(a,left,i);
        MS(a,i+1,right);
        M(a,b,left,i,right);
        C(a,b,left,right);
    }
    else cout<<b[0];
}
int main() {
    int n;
    cin>>n;
    int *a=new int(n);
    for (int i=0; i<n; i++) {
        cin>>a[i];
    }
    MS(a,0,n-1);

    for(int j=0;j<n;j++)
        cout<<a[j]<<endl;
    return 0;
}

  • 写回答

2条回答 默认 最新

  • threenewbee 2017-03-17 06:17
    关注

    数组的边界条件,注意下标从0开始算。调试下就知道。

    评论

报告相同问题?

悬赏问题

  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波
  • ¥15 针对曲面部件的制孔路径规划,大家有什么思路吗
  • ¥15 钢筋实图交点识别,机器视觉代码
  • ¥15 如何在Linux系统中,但是在window系统上idea里面可以正常运行?(相关搜索:jar包)
  • ¥50 400g qsfp 光模块iphy方案
  • ¥15 两块ADC0804用proteus仿真时,出现异常
  • ¥15 关于风控系统,如何去选择