是什么都不是 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开始算。调试下就知道。

    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制