本文介绍了mergeesort算法在c ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码

#include <iostream>
using namespace std;
void merge(int c[],int a[],int n,int b[],int m){
         for (int i=0,j=0,k=0;k<n+m;k++){

             if (i==n) {  c[k]=b[j++]; continue;}
             if (j==m ){  c[k]=a[i++];continue;}

             c[k]=(a[i]<b[j])? a[i++]:b[j++];

         }



}
void mergesort(int a[],int b[],int l,int r){
if (l>r)  return ;
     int m=(l+r)/2;

     mergesort(b,a,l,m);
     mergesort(b,a,m+1,r);

 merge(a+l,b+l,m-l+1,b+m+1,r-m);

}
int main(){


    int a[]={12,4,2,5,3,6,7,8,10,11};
const   int n=sizeof(a)/sizeof(int);
int b[n];
mergesort(a,b,0,n-1);
    for (int i=0;i<n;i++){

        cout<<b[i]<< "  ";

    }




     return 0;
}

但这里是这样的警告

1>------ Rebuild All started: Project: mergesort, Configuration: Debug Win32 ------
1>  mergesort.cpp
1>d:\c++_algorithms\mergesort\mergesort\mergesort.cpp(24): warning C4717: 'mergesort' : recursive on all control paths, function will cause runtime stack overflow
1>  mergesort.vcxproj -> D:\c++_algorithms\mergesort\Debug\mergesort.exe
========== Rebuild All: 1 succeeded, 0 failed, 0 skipped ==========

请帮我修复它

我已更新我的代码

推荐答案

mergesort()需要检测是否要求对长度列表一个,如果是,立即返回。此外,我可能错了,但我认为调用merge()在之后递归调用mergesort()。

mergesort() needs to detect whether it's been asked to sort a list of length one, and if so, return immediately. Also, I could be wrong, but I think the call to merge() goes after the recursive calls to mergesort().

这篇关于mergeesort算法在c ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 22:24