问题描述
我正在学习堆,我想使用 MinHeap 在 Javascript 中实现堆排序算法。 问题是我一直得到一个未排序的数组。 我什至试图将一个工作算法从 C++ 翻译成 Javascript。 原始算法链接:https://www.geeksforgeeks.org/heap-sort-for-decreasing-order-using-min-heap/
C++:
document.querySelectorAll()
Javascipt(翻译后的代码):
// To heapify a subtree rooted with node i which is
// an index in arr[]. n is size of heap
void heapify(int arr[],int n,int i)
{
int smallest = i; // Initialize smalles as root
int l = 2 * i + 1; // left = 2*i + 1
int r = 2 * i + 2; // right = 2*i + 2
// If left child is smaller than root
if (l < n && arr[l] < arr[smallest])
smallest = l;
// If right child is smaller than smallest so far
if (r < n && arr[r] < arr[smallest])
smallest = r;
// If smallest is not root
if (smallest != i) {
swap(arr[i],arr[smallest]);
// Recursively heapify the affected sub-tree
heapify(arr,n,smallest);
}
}
// main function to do heap sort
void heapSort(int arr[],int n)
{
// Build heap (rearrange array)
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr,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);
}
}
当我尝试使用这个数组 arr = [1,2,7,3,5] 时,heapSort 算法返回这个表 [1,5 ];
你能帮我弄清楚JS实现有什么问题吗? 提前致谢!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)