gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:21:18 25 4
gpt4 key购买 nike

我是 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

关于C++:HeapSort 函数输出错误的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33586183/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com