[英]Why does my recursive code result in a stack overflow error?
This code is given in the book "Introduction to Algorithms". 该代码在“算法简介”一书中给出。 For this I used 1 indexed array
为此,我使用了1个索引数组
#include <cstdlib>
#include <iostream>
using namespace std;
int n=6;
int x[1000];
void max_heapify(int a[],int i)
{
int left=2*i;
int right=2*i+1;
int largest=i;
if( left<=n && a[left]>a[largest]){
largest=left;
}
if(right<=n && a[right]>a[largest])
{
largest=right;
}
if(largest!=i)
{
int t=a[i];
a[i]=a[largest];
a[largest]=t;
}
max_heapify(a,largest);
}
void max_heap(int a[])
{
int heap_length=n;
for(int i=n/2;i>=1;i--)
max_heapify(a,i);
}
int main(int argc, char *argv[])
{
for(int i=1;i<=n;i++)
cin>>x[i];
max_heap(x);
cout<<endl;
for(int i=1;i<=n;i++)
cout<<x[i]<<" ";
// system("PAUSE");
//return EXIT_SUCCESS;
return 0;
}
For this input 对于此输入
1 5 7 8 3 9
on ideone.com it writes "time limit exceeded". 在ideone.com上,它写有“ time limit beyond”。 I have tried the debugger in Visual Studio, with the following result
我在Visual Studio中尝试了调试器,结果如下
First-chance exception at 0x001c14d9 in max_heap.exe: 0xC00000FD: Stack overflow. Unhandled exception at 0x001c14d9 in max_heap.exe: 0xC00000FD: Stack overflow. First-chance exception at 0x001c14d9 in max_heap.exe: 0xC0000005: Access violation writing location 0x002c0ffc. Unhandled exception at 0x001c14d9 in max_heap.exe: 0xC0000005: Access violation writing location 0x002c0ffc. The program '[6044] max_heap.exe: Native' has exited with code -1073741819 (0xc0000005).
What is wrong? 怎么了?
Your max_heapify
will always end up in another recursion. 您的
max_heapify
将始终以另一个递归结束。 There is no termination happening in any of the control paths. 在任何控制路径中都没有终止发生。 This causes your stack overflow.
这会导致堆栈溢出。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.