C++:HeapSort 函数输出错误的数字

C++: HeapSort function outputting wrong numbers

我对 C++/算法比较陌生,我不太确定我的 heapSort 函数有什么问题。给定数字(6、2、9、1、5),我输出了以下不正确的数字:

9
4197040
2
4196422
6

感谢观看。

#include <iostream>

using namespace std;

void heapSort(int arr [], int size);
void reheapDown(int arr[], int root, int bottom);
void swap(int & num1, int & num2);

int main()
{
   int arr[5] = {6, 2, 9, 1, 5};

   heapSort(arr, 5);

   for (int i = 0; i < 5; i++)
   cout << arr[i] << endl;

   return 0;
}

void heapSort(int arr [], int size){

    int i;

    for (i = size/2 -1; i >= 0; i--)
    reheapDown(arr, i, size-1);

    for (i = size - 1; i >= 1; i--){
    swap(arr[0], arr[i]);
    reheapDown(arr, 0, i-1);

    }

}

void reheapDown(int arr[], int root, int bottom){

    int max, right, left;

    left = root * 2 + 1;
    right = root * 2 + 2;

    if (left <= bottom)

        max = left;

    else{
        if (arr[left] <= right)
        max = right;
        else
        max = left;
    }
    if (arr[root] < arr[max]){

        swap(arr[root], arr[max]);
        reheapDown(arr, max, bottom);
    }
}

void swap(int & num1, int & num2){

    int temp;

    temp = num1;
    num1 = num2;
    num2 = temp;

}

至少有一个问题是您正在越界访问:

void reheapDown(int arr[], int root, int bottom){

    int max = 0;

    int left = root * 2 + 1;
    int right = root * 2 + 2;


    if (left <= bottom)
        max = left;
    else{
        if (left < 0){
            throw std::runtime_error("Uh oh, left is less than zero");
        }
        if (left > 4){
            throw std::runtime_error("Uh oh, left is greater than 4");
        }

        if (arr[left] <= right)
            max = right;
        else
        max = left;
    }
    if (arr[root] < arr[max]){
        if (root < 0){
            throw std::runtime_error("Uh oh, root is less than zero");
        }
        if (root > 4){
            throw std::runtime_error("Uh oh, root is greater than 4");
        }
        if (root < 0 || root > 4){
            throw std::runtime_error("Uh oh");
        }
        swap(arr[root], arr[max]);
        reheapDown(arr, max, bottom);
    }
}

将输出:

terminate called after throwing an instance of 'std::runtime_error'
  what():  Uh oh, left is greater than 4