堆排序错误:围绕变量堆栈损坏?
问题描述:
我正在为作业实现堆排序。我们必须按照她在课堂上使用她的伪代码的方式来做,否则我们不会得到信任。堆排序错误:围绕变量堆栈损坏?
即时得到一个运行时错误:围绕变量“heapArray” 堆栈已损坏。我和调试器一起玩,仍然无法弄清楚是什么导致了错误。我很确定它与HeapSort()函数中的For循环有关。谁能帮忙?
void HeapSort(int heapArray[])
{
int heap_size = SIZE;
int n = SIZE;
int temp;
Build_Max_Heap(heapArray);//function not implemented, only declared for compile
for(int i = n; i >=2; i--) //***I think error coming from something in here
{
temp = heapArray[1];
heapArray[1] = heapArray[i];
heapArray[i] = temp;
heap_size = heap_size-1;
Max_Heapify(heapArray,1);//function not implemented, only declared for compile
}
return;
}
int main()
{
int heapArray[SIZE] = { 5 ,99, 32, 4, 1, 12, 15 , 8, 13, 55 };
HeapSort(heapArray);
cout << endl;
return 0;
}
答
错误是:
for(int i = n; i >=2; i--)
你必须从n-1
开始,数组索引从0正确的方式开始要做的应该是
for(int i = n -1; i >=1; --i)
如果从n
开始,数组索引超出界限错误。很可能您书中的伪代码(为了方便起见)使用从1到n
的数组索引,但是在使用C++编写的实际程序中,我们应该从0开始到n-1
。
答
你正在编写出界在
for(int i = n; i >=2; i--)
{
temp = heapArray[1];
heapArray[1] = heapArray[i]; //THIS IS WRONG
heapArray[i] = temp; //
在C数组从0到n-1。 heapArray声明为SIZE大小。
应该更像:
for(int i = n - 1; i >=2; i--) //Now you start from n-1
{
temp = heapArray[1];
heapArray[1] = heapArray[i];
heapArray[i] = temp;