请帮助。我已经对其进行了审查,似乎丢失了该错误。它似乎退出了函数Max_Heapify,并且没有运行我的第二个循环来打印排序后的数组。这是我已经上交的一项作业,但我正在尝试学习自己的方式上的错误,以确保我可以在测试中表现出色。
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
// declare global variable of heap size
int heap_size = 7;
// function to determine left child node of the tree
int Left(int i){
return 2*i+1;
}
// function to determine right child node of the tree
int Right(int i){
return 2*i + 2;
}
// create heap tree
void Max_Heapify (int array[], int index){
int left_child_index = Left(index);
int right_child_index = Right(index);
int largest;
// check if left child is smaller than heap size and if left child is bigger than parent
// if so, save variable as largest value, otherwise, largest value will stay as index
if ( (left_child_index < heap_size) && (array[left_child_index] > array[index]) )
largest = left_child_index;
else largest = index;
// check if right child is smaller than heap and if bigger than largest value
if ((right_child_index < heap_size) && (array[right_child_index] > array[largest]) )
largest = right_child_index;
// exchange largest values
if (largest != index)
swap(array[index], array[largest]);
Max_Heapify(array,largest);
}
// check leaves
void Build_Max_Heap(int array[]){
for (int i = (heap_size / 2 ) - 1; i >= 0; i--)
Max_Heapify (array, i);
}
void Heapsort(int array[]) {
Build_Max_Heap(array);
for (int i = heap_size-1; i >= 0; i--){
swap(array[0], array[i]);
Max_Heapify(array,0);
}
}
int main(){
int arr[7] = {21, 9, 50, 7, 6, 33, 77};
cout << "Non Heapified Array: " << endl;
for (int i = 0; i < heap_size; i++){
cout << arr[i] << endl;
}
Heapsort(arr);
for (int i = 0; i < heap_size; i++){
cout << arr[i]<< endl;
}
}
您的MaxHeapify
永不终止。仅当MaxHeapify
不是largest
时,才应调用i
。如果largest
为i
,则此处无需执行任何操作,因为元素已被堆积。
if (largest != index){
swap(array[index], array[largest]);
Max_Heapify(array,largest);
}