c++ - 堆排序 C++ 调试
问题描述
我的堆排序不正确并给出错误的输出。我想我已经完成了所有步骤,还有什么我遗漏的吗?
我很确定我的 heapify 方法,但我不知道 heapsort 方法上的循环。
#include <iostream>
using namespace std;
void swap(int* a, int* b) // swap using swap(&var1, &var2)
{
int c = *a;
*a = *b;
*b = c;
}
void heapify(int arr[], int size)
{
// For some reason others have a third parameter for heapify "i", or "max".
// DECLARE VARIABLES
int i;
// int left = (2*i) + 1;
// int right = (2*i) + 2;
int parent = (i-1)/2;
// Loop through entire array, check parent, then test
for(i = size-1; i>1; i--) {
if(arr[i] > arr[parent]) {
swap(arr[i], arr[parent]);
// Assuming that the swap is complete
}
}
// Looks array from bottom to top, guarantees highest at the top
}
void heapsort(int arr[], int size)
{
heapify(arr, 5);
for(int i=size-1; i>=0; i--) { // i > 0 and i >= 0 is the same?
swap(arr[0], arr[i]);
heapify(arr, i);
}
}
int main ()
{
int arr[5] = {2,4,6,1,9};
heapsort(arr, 5);
for(int i=0; i<5; i++) {
cout<<arr[i]<<" ";
}
return 0;
}
解决方案
Heapify 对以第 i 个节点为根的子树进行排序,这就是您提到的第三个参数。参数i
传递给heapify()
from heapSort()
,然后在内部使用heapify()
。此外,left
andright
在您的代码中被注释掉,因此您的代码不会检查子节点是否大于父节点。看看这个实现:
#include <iostream>
using namespace std;
void heapify(int* arr, int n, int i) // To heapify a subtree rooted with node i which is an index in arr[]. n is size of heap
{
int largest = i; // Initialize largest as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is larger than root
if (l < n && arr[l] > arr[largest])
largest = l;
// If right child is larger than largest so far
if (r < n && arr[r] > arr[largest])
largest = r;
// If largest is not root
if (largest != i)
{
swap(arr[i], arr[largest]);
// Recursively heapify the affected sub-tree
heapify(arr, n, largest);
}
}
int* heapSort(int* arr, int n) // uses heapify returns pointer to sorted array
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
// One by one extract an element from heap
for (int i = n - 1; i >= 0; i--)
{
// Move current root to end
swap(arr[0], arr[i]);
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
return arr;
}
int main()
{
int arr[] = {3, 6, 1, 3, 2, 9, 7, 8, 5, 6, 4, 9, 2 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Unsorted numbers: \n";
print_array(arr, n);
cout << "Sorted array: \n";
int* sorted_array = heapSort(arr, n);
print_array(sorted_array, n);
return 0;
}
推荐阅读
- discord.js - 让不和谐的机器人自动加入服务器
- jenkins - 在 ECS 中使用 EFS 时出错,返回未知文件系统类型“efs”
- c# - 如何设置列表框中项目的大小?
- c# - .NET CEF Sharp 绑定 WebSocket 请求 - 未引发/调用 OnBeforeResourceLoad 方法
- javascript - 我可以在同一个项目中拥有 Django url 和 Vue 路由吗?
- c - 优化加权移动平均线
- javascript - 如何使用“nprogreess”?
- python-3.x - 使用 pyinstaller 和 cx_Freeze 时经常出现错误
- dictionary - 映射集合 Discord JS
- bash - 源目录似乎不包含 CMakeLists.txt