堆排序算法代码

#include <iostream>
#include <algorithm>

using namespace std;

void HeapAdjust(int *arr, int size, int element);
void BuildHeap(int *arr, int size);
void HeapSort(int *arr, int size);

int main()
{
    int a[] = { 0,16,20,3,11,17,8 };
    HeapSort(a, sizeof(a) / sizeof(a[0]));

    for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
    {
        cout << a[i] << " ";
    }

    return 0;
}

void HeapAdjust(int *arr, int size, int element)  //调整堆
{
    int leftchild = element * 2 + 1, rightchild = leftchild + 1;
    int min_index = element;
    if (element <= (size - 1) / 2) { //对非叶结点进行调整(注意索引关系)
        if (leftchild < size && arr[leftchild] < arr[min_index])  //如果存在左孩子,对左孩子进行处理
            min_index = leftchild;
        if (rightchild < size && arr[rightchild] < arr[min_index])  //如果存在右孩子,对右孩子进行处理
            min_index = rightchild;

        if (min_index != element)
        {
            swap(arr[element], arr[min_index]);
            HeapAdjust(arr, size, min_index);
        }
    }
}

void BuildHeap(int *arr, int size)       //构建最小堆(时间复杂度为lg n)
{
    for (int i = (size - 1) / 2; i >= 0; i--)
        HeapAdjust(arr, size, i);
}

void HeapSort(int *arr, int size)      //堆排序(时间复杂度为nlg n):它是由构建堆和调整堆组合完成的
{
    BuildHeap(arr, size);

    while (size)
    {
        swap(arr[0], arr[size - 1]);
        size--;
        HeapAdjust(arr, size, 0);
    }
}
  • 上述代码是构建最小堆
    这里写图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值