尝试堆插入时访问冲突写入位置

时间:2014-03-11 22:49:02

标签: c++ heap

#include <iostream>
using namespace std;



int getParent(int);
int getLeftChild(int);
int getRightChild(int);
void swap(int&, int&);
void heapify(int A[], int);
void build_heap(int A[]);
void printArray(int A[], int);
void heapInsert(int A[], int);

int main()

{
int parent;
int right;
int left;
int A[10]={4,1,3,2,16,9,10,14,8,7};



heapify(A,3);

cout << "Print Array A:" << endl;
printArray(A, 10);
cout << endl;
build_heap(A);
parent=getParent(5);
left=getLeftChild(3);
right=getRightChild(3);
cout<<"Parent of node 5 is the node " << parent << endl;
cout<<"Left child of node 3 is the node " << left << endl;
cout<<"Left child of node 3 is the node " << right <<endl << endl;
cout << "Print Heap A:" << endl;
printArray(A, 10);
cout << endl;
cout << "After inserting the number 20:" << endl;
heapInsert(A, 20);
build_heap(A);
printArray(A, 11);
cout << endl;
cout << "After inserting the number 17:" << endl;
heapInsert(A, 17);
build_heap(A);
printArray(A, 12);

system("pause");
return 0;


}

void heapInsert(int A[], int Item)
{
 int i = 10;
 A[i] ++;
 i = A[i];
  while (i > 1  &&  A[getParent(i)] < Item)
    {
        A[i] = A[getParent(i)];
        i = getParent(i);
    }
    A[i] = Item;
}

当我尝试增加堆的大小并使用heapInsert函数调用插入新值时,问题出现了。我的所有其他功能都很好,但我不知道从哪里开始。

1 个答案:

答案 0 :(得分:1)

int A[10]={4,1,3,2,16,9,10,14,8,7};

int i = 10;
 A[i] ++;

数组A的最大索引是9。