c++ 堆排序

强烈推荐视频: 堆排序(heapsort)

代码:

#include <iostream>
#include <stdlib.h>
using namespace std;

void heapify(int tree[], int n, int i)
{
    if (i >= n)
        return;

    int c1 = 2 * i + 1;
    int c2 = 2 * i + 2;
    int max = i;
    if (c1 < n && tree[c1] > tree[max])
        max = c1;
    if (c2 < n && tree[c2] > tree[max])
        max = c2;

    if (max != i)
    {
        swap(tree[max], tree[i]);
        heapify(tree, n, max);
    }
}

void build_head(int tree[], int n)
{
    int last_node = n - 1;
    int parent = (last_node - 1) / 2;
    for (int i = parent; i >= 0; i--)
    {
        heapify(tree, n, i);
    }
}

void heap_sort(int tree[], int n)
{
    build_head(tree, n);
    for (int i = n - 1; i >= 0; i--)
    {
        swap(tree[i], tree[0]);
        heapify(tree, i, 0);
    }
}

int main()
{
    int tree[] = {2, 5, 3, 1, 10, 4};
    heap_sort(tree, 6);
    for (int i = 0; i < 6; i++)
        cout << tree[i] << " ";
    cout << endl;
    system("pause");
    return 0;
}

 

原文链接: https://www.cnblogs.com/r1-12king/p/13326600.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    c++ 堆排序

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/367403

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 下午5:46
下一篇 2023年3月2日 下午5:46

相关推荐