首页 > 编程语言 > 详细

c++ 堆排序

时间:2020-07-17 09:36:36      阅读:50      评论:0      收藏:0      [点我收藏+]

强烈推荐视频: 堆排序(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;
}

 

c++ 堆排序

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!