问题
i have following code
#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;
}
but here is such warning
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 ==========
please help me to fix it
i have updated my code
回答1:
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().
回答2:
Your recursive call should have a terminating condition so that the recursive calls would end at some point.
I think adding the following condition at the beginning of your mergesort function solves the problem:
if(l>r)
return;
回答3:
You need to have a base case, which probably means that you should check whether the size of the array you are sorting is =1, and if it is, you return that particular element itself.
In code, this would mean checking something like
l==r
Also, logically, merge should be called after you have sorted the two sub-arrays.
回答4:
you need to specify a base case in your mergeSort function! and also, in the mergeSort algorithm, the call to merge comes after the recursive call to the left and right subarrays
来源:https://stackoverflow.com/questions/4199224/mergesort-algorithm-in-c