简体   繁体   English

堆排序错误:变量周围的堆栈已损坏?

[英]Heap Sort error: Stack around variable was corrupted?

I am implementing Heap Sort for an assignment. 我正在为任务实施堆排序。 We have to do it the same way she did in class with her pseudocode, or else we dont get credit. 我们必须像使用伪代码在课堂上那样做,否则我们不会获得荣誉。

Im getting a runtime error: Stack around the variable 'heapArray' was corrupted . 我收到了运行时错误: 变量'heapArray'周围的堆栈已损坏 I played with the debugger, and still was not able to figure out what is causing the error. 我玩过调试器,但仍然无法弄清楚是什么导致了错误。 I am pretty sure it has something to do with my For loop in the HeapSort() function. 我很确定它与HeapSort()函数中的For循环有关。 Can anyone help? 有人可以帮忙吗?

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;
}

You are writing out of bounds at 您正在超越范围

for(int i = n; i >=2; i--) 
{
temp = heapArray[1];
heapArray[1] = heapArray[i];  //THIS IS WRONG
heapArray[i] = temp;          //

In c arrays go from 0 to n-1. 在c数组中,从0到n-1。 heapArray is declared with size SIZE. 使用大小为SIZE声明heapArray。

Should be more like: 应该更像:

for(int i = n - 1; i >=2; i--) //Now you start from n-1
{
temp = heapArray[1];
heapArray[1] = heapArray[i];
heapArray[i] = temp; 

Error is: 错误是:

for(int i = n; i >=2; i--) 

You have to start from n-1 since array index starts from 0. Correct way to do should be 您必须从n-1开始,因为数组索引从0开始。正确的方法应该是

for(int i = n -1; i >=1; --i)

array index out of bound error if you start from n . 如果从n开始,则数组索引超出范围错误。 It is highly likely that pseudocode in your book (for convenience purpose) use array index from 1 to n , but in real program with C++, we should start from 0 to n-1 instead. 为了方便起见,您的书中的伪代码很有可能使用从1到n数组索引,但是在使用C ++的实际程序中,我们应该从0到n-1开始。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM