将 maxHeap 排序更改为 minHeap 排序

发布于 2024-12-27 18:55:25 字数 658 浏览 4 评论 0原文

我正在努力弄清楚如何将 maxHeap 更改为 minHeap。我目前有一个 maxHeap 算法正在运行,但我想知道如何更改它。这是我使用过的 maxHeap:

public static int [][] fixheap(int heap[][], int n, int i){
    int j=2*i;
    int weight = heap[i][0];

    while (j<=n){
        if((j<n) && heap[j][0] < heap[j+1][0])
            j++;
        if(weight >= heap[j][0]) break;
        else 
        heap[j/2][0] = heap[j][0]; 

        j=j*2;
    }

    heap[j/2][0]= data;

    return heap;
}

public static void makeheap(int heap[][], int n){

    for (int i=n/2; i>=0; i--){
        fixheap(heap, n ,i);
    }   
}

我尝试反转某些看似相关的标志,但是我还没有找到 minHeap。任何帮助都会很棒,谢谢。

I am struggling to work out how to change a maxHeap to a minHeap. I currently have a maxHeap algorithm working but I would like to know how to change it. This is the maxHeap I have used:

public static int [][] fixheap(int heap[][], int n, int i){
    int j=2*i;
    int weight = heap[i][0];

    while (j<=n){
        if((j<n) && heap[j][0] < heap[j+1][0])
            j++;
        if(weight >= heap[j][0]) break;
        else 
        heap[j/2][0] = heap[j][0]; 

        j=j*2;
    }

    heap[j/2][0]= data;

    return heap;
}

public static void makeheap(int heap[][], int n){

    for (int i=n/2; i>=0; i--){
        fixheap(heap, n ,i);
    }   
}

I have tried reversing certain signs that seem relevant however, I have not found the minHeap. Any help would be great, thanks.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

慈悲佛祖 2025-01-03 18:55:25

最小堆和最大堆之间的唯一区别是比较器。如果您有一个正常运行的最大堆结构,则只需翻转比较器即可。

查看 Amazon 上的算法简介。最大堆结构有非常详细的描述,可以在预览或“Look Inside”功能中找到。

The only difference between a min and max heap is the comparator. If you have a functioning max-heap structure, you should only have to flip the comparator.

Check out Introduction to Algorithms on Amazon. The max-heap structure is described in great detail and is available in the preview or "Look Inside" feature.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文