无法在我的堆排序代码中找到错误。没有正确执行。 C++

Not able to find error in my Heap Sort Code. Not executing properly. C++

请帮忙。我已经检查过了,似乎遗漏了错误。它似乎退出了函数 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 永远不会终止。仅当 largest 不是 i 时才应调用 MaxHeapify。如果 largesti,那么这里不需要做任何事情,因为元素已经堆化了。

if (largest != index){
    swap(array[index], array[largest]);
    Max_Heapify(array,largest);
}