堆排序

堆排序

堆排序以二叉形式。

以数组形式表示。a[1] 是二叉堆的跟结点,每个结点的有左右子结点。规定每个结点的值大于其子节点的堆叫最大堆,小于的叫最小堆。

无序数组通过建堆的方式建立成一个最大或最小堆。

算了 ,说不清,上代码。

代码:

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100;
int a[MAXN] = {0,4,1,3,2,16,9,10,14,8,7};//10
int n = 10;//数的个数

void Max_Heap(int x,int n)
{
    //维护根节点为x的最大堆
    //n为数组长度
    int pos = x;
    int left_pos = x<<1;
    int right_pos = (x<<1) + 1;
    if (left_pos <= n && a[pos] < a[left_pos])
        pos = left_pos;
    if (right_pos <= n && a[pos] < a[right_pos])
        pos = right_pos;
    if (pos != x)
    {
        int tmp = a[pos];
        a[pos] = a[x];
        a[x] = tmp;
        Max_Heap(pos,n);
    }
    return ;
}

void Min_Heap(int x,int n)
{
    //维护根节点为x的最小堆
    //n为数组长度
    int pos = x;
    int left_pos = x<<1;
    int right_pos = (x<<1) + 1;
    if (left_pos <= n && a[pos] > a[left_pos])
        pos = left_pos;
    if (right_pos <= n && a[pos] > a[right_pos])
        pos = right_pos;
    if (pos != x)
    {
        int tmp = a[pos];
        a[pos] = a[x];
        a[x] = tmp;
        Min_Heap(pos,n);
    }
    return ;
}

void Build_Max_Heap(int x,int n)
{
    //给数组1-x位置建立最大堆,1为根节点
    //n为数组长度
    for (int i = x/2;i > 0;i--)
        Max_Heap(i,n);
}

void Build_Min_Heap(int x,int n)
{
    //给数组1-x位置建立最小堆,1为根节点
    //n为数组长度
    for (int i = x/2;i > 0;i--)
        Min_Heap(i,n);
}

void Print_Max_Heap(int x)
{
    //输出最大堆
    while (x)
    {
        cout << a[1] << ' ';
        int tmp = a[x];
        a[x] = a[1];
        a[1] = tmp;
        Max_Heap(1,x-1);//最后一个结点不使用,所以维护长度减1
        x--;
    }
}

void Print_Min_Heap(int x)
{
    //输出最小堆
    while (x)
    {
        cout << a[1] << ' ';
        int tmp = a[x];
        a[x] = a[1];
        a[1] = tmp;
        Min_Heap(1,x-1);
        x--;
    }
}

int main()
{
    Build_Max_Heap(n,n);
    Print_Max_Heap(n);
    Build_Min_Heap(n,n);
    Print_Min_Heap(n);


    return 0;
}
//运行结果
//16 14 10 9 8 7 4 3 2 1 
//1 2 3 4 7 8 9 10 14 16 

  

posted @ 2019-01-20 00:19  YDDDD  阅读(102)  评论(0编辑  收藏  举报