堆排序C++

来源:互联网 发布:淘宝怎么装修店铺首页 编辑:程序博客网 时间:2024/05/24 20:06
#include<iostream>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
int left(int x)
{
    return (x << 1) + 1;
}
int right(int x)
{
    return (x << 1) + 2;
}
void Swap(int *a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}
void MaxHeapify(int data[], int i, int n)
{
    int l = left(i);
    int r = right(i);
    int largest = i;
    if(l < n && data[largest] < data[l]) largest = l;
    if(r < n && data[largest] < data[r]) largest = r;
    if(largest != i)
    {
        Swap(&data[largest], &data[i]);
        MaxHeapify(data, largest, n);
    }
}
void BuildMaxHeap(int data[], int n)
{
    for(int i = n / 2 - 1; i >= 0; i--)
    {
        MaxHeapify(data, i, n);
    }
}
void HeapSort(int data[], int n)
{
    if(nullptr == data || n <= 0)
    {
        return ;
    }
    int heap_size = n - 1;
    BuildMaxHeap(data, heap_size);
    for(int i = n - 1; i >= 1; --i)
    {
        Swap(&data[0], &data[i]);
        BuildMaxHeap(data, heap_size);
        --heap_size;
    }
}
int main()
{
    int mydata[10] = {2, 1, 3, 4, 6, 5, 8, 7, 10, 9};
    HeapSort(mydata, 10);
    for(int i = 0; i <= 9; i++)
    {
        cout<<mydata[i]<<" ";
    }
    return 0;
}

阅读全文
'); })();
0 0
原创粉丝点击
热门IT博客
热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 排毒瑜伽 瑜伽健身 男人瑜伽 瑜伽长高 瑜伽app 密宗瑜伽 瑜伽网站 瑜伽种类 瑜伽猫式 瑜伽的作用 瑜伽初学者 瑜伽的种类 瑜伽歌曲 瑜伽英文 少儿瑜伽 瑜伽图 瑜伽垫子 瑜伽体式图 瑜伽英语 健身瑜伽 流瑜伽体式 瑜伽初级 瑜伽的坏处 瑜伽的起源 瑜伽课程 力量瑜伽 瑜伽呼吸法 男性瑜伽 自学瑜伽 瑜伽团购 瑜伽基本 瑜伽机构 瑜伽的课程 美国瑜伽 瑜伽好不好 高级瑜伽馆 瑜伽有哪些 瑜伽减肥瑜伽 下载瑜伽 专业瑜伽馆 瑜伽的价格