일반적인 배열에서 힙 배열을 작성하는 프로그램을 작성 중이며 작동하지 않습니다. 우리는 rebuildHeap 함수를 작성하는 데 사용했던이 sudo 코드를 사용해야하지만 잘못된 것을 알지 못합니다. 누군가 실수를 발견 할 수 있었습니까?힙 배열이 작동하지 않습니다.
rebuildHeap is used after the replacement node has taken the place of root
rebuildHeap(heap, index, lastIndex)
1 if (index * 2 + 1 <= lastIndex)
1 leftKey = heap[index*2+1].key
2 if (index * 2 + 2 > lastIndex)
1 largeChildIndex = index * 2 + 1
3 else
1 rightKey = heap[index*2+2].key
2 if (leftKey > rightKey)
1 largeChildIndex = index * 2 + 1
3 else
1 largeChildIndex = index * 2 + 2
4 end if
4 end if
5 if (heap[index].key < heap[largeChildIndex].key)
1 swap (heap[index], heap[largeChildIndex])
2 rebuildHeap(heap, largeChildIndex, lastIndex)
6 end if
2 end if
는이 때문에 처음에는 INT의 배열을 만들고 내가 힙 배열이 완료 될 때까지 rebuildHeap를 호출 힙 함수를 만들고 실행 한 후 어떤 임의의 값을 저장 .. 내 코드입니다. 편집을 할
는 배열 크기 .. 나는 의사의 번역이 잘못된 것을 강조하고자하는 모든
void rebuildHeap(int heap[], int index, int lastindex) {
int leftkey = 0 ;
int largeChildIndex = 0;
int rightkey = 0;
cout << endl;
if (heap[index*2+1] <= heap[lastindex])
{
leftkey = heap[index*2+1];
cout <<" index : " << index*2+1 << " leftkey " << leftkey << endl;
cout <<" index : " << lastindex << " heap[lastindex] = " << heap[lastindex] << endl;
if ((heap[index * 2+ 2]) > heap[lastindex])
largeChildIndex = (index* 2) +1;
else
{
rightkey = heap[index*2+2];
if (leftkey > rightkey)
largeChildIndex = index * 2 +1;
else
largeChildIndex = index*2+2;
}
}
if (heap[index] < heap[largeChildIndex]) {
swap(heap[index], heap[largeChildIndex]);
rebuildHeap(heap, largeChildIndex, lastindex);
}
}
void swap (int &a, int &b) {
int temp = b;
b = a;
a = temp;
}
int main(int argc, const char * argv[])
{
int a[] = {3, 7, 12, 15, 18, 23, 4, 9, 11, 14, 19, 21};
int length = (sizeof(a)/sizeof(a[0]));
for (int i = length/2-1; i >= 0; i--) {
rebuildHeap(a, i, length-1);
cout << " i " << i;
}
for (int i = 0; i < length; i++) {
cout << endl<< a[i] << endl;
}
};
'int size = (sizeof (& heap));'줄이 옳지 않은 것 같습니다. '크기'란 무엇입니까? –
배열의 길이를 저장합니다. 배열에있는 요소의 수는 – emsqre
입니다. 이것을 함수의 인수로 전달해야합니다. 'sizeof (& heap)'는 여러분의 환경에있는 포인터의 크기와 같습니다 - 대부분 4 ~ 8 개입니다. –