码迷,mamicode.com
首页 > 编程语言 > 详细

c++ 堆排序

时间:2020-07-17 01:23:04      阅读:99      评论:0      收藏:0      [点我收藏+]

标签:eid   tar   class   stream   pause   --   video   ace   arc   

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

标签:eid   tar   class   stream   pause   --   video   ace   arc   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!