此代码在“算法简介”一书中给出。为此,我使用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;
}
有关ideone.com此输入
1 5 7 8 3 9
其写入 “超过时限”。我试过了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).
什么错?
你试过调试吗?我的意思是真正的调试,而不仅仅是在调试模式下运行?一步一步的操作等你的递归可能太深,调试你的递归函数,找出它在你期望的时候不会停止的原因。 – littleadv 2012-03-17 21:46:25