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
相关文章:
- 输出错误,问题是找到总和5000位数字cpp
- 在使用堆栈为下一个最大数字编写代码时面临 SIGSEGV(分段错误)
- 错误含义;以二进制形式打印数字
- C++ 分段错误:11 错误,同时编码将两个数字相加的链接列表
- 我如何在一个 if 语句中声明所有数字我尝试通过其他方式声明所有数字,如果一个接一个,但似乎代码有逻辑错误
- 分布MPI散点错误的数字
- 涉及模运算符优先级的错误以及C++中具有大数字的括号
- Arduino IDE 错误 - 无法找到数字文字运算符"运算符""f900ff"
- 为什么C++显示错误的数字?
- 错误:数字常量 #define BOOT_PROTOCOL 0x00 之前的预期'>'
- 我的代码似乎在查找最大数字时存在语法错误
- Fibbonaci 递归代码返回错误值,始终返回下一个数字
- C++:按数字排序链表错误
- isdigit() 和 isalnum() 给出错误,因为输入是一个常量字符并且无法转换。其他可能查看输入是否为数字的方法?
- 一个数字的提升精神解析器的分段错误
- 错误:数字常数之前的预期无限制ID:std :: array和std ::向量大小分配
- C++数组中的错误数字
- 构造函数错误:错误:数字常量之前的预期“”,“”或“..”
- [错误]数字常量之前的预期标识符.-setlocale
- 错误:“数字”之前的预期类型说明符