堆排序

#include <stdio.h>
#include <assert.h>
#include <windows.h>

void PrintArray(int* array, int size)
{
    int i = 0;
    for(; i < size; i++)
        printf("%d ", array[i]);

    printf("\n");
}

void Swap(int* pLeft, int* pRight)
{
    int temp = 0;
    assert(pLeft);
    assert(pRight);

    temp = *pLeft;
    *pLeft = *pRight;
    *pRight = temp;
}

void HeapAdjust(int* array, int parent, int size)//堆的调整,向下调整法,从最后一个非叶子节点 
                                                 //开始调整
{
    int child = parent*2 + 1;
    while(child < size)
    {
        if(child+1 < size && array[child+1] > array[child])//如果右孩子存在且比左孩子大
            child += 1;//让child标记右孩子

        if(array[parent] < array[child])//双亲节点的值小于大孩子
        {
            Swap(&array[parent], &array[child]);//交换这两个节点的值,让双亲节点的值大于两个                
                                                //孩子的值
            parent = child;//用parent标记child节点
            child = parent*2 + 1;//找到新的child节点继续调整。因为没调整一个节点,就有可能打乱 
                                 //前面排好的序
        }
        else
            return;
    }
}

void HeapSort(int* array, int size)
{
    int end = size - 1;
    int root = ((size - 2)>>1);

    for(; root >= 0; --root)//每调整完一个非节点,就调整紧挨着他的前边那个节点
        HeapAdjust(array, root, size);//堆调整

    while(end)//堆的删除:实际上是删除堆顶元素
    {
        Swap(&array[0], &array[end]);
        HeapAdjust(array, 0, end);
        --end;
    }
}

void TestSort()
{
    int array[] = {2, 5, 4, 9, 3, 6, 8, 7, 1, 0};
    PrintArray(array, sizeof(array)/sizeof(array[0]));
    HeapSort(array, sizeof(array)/sizeof(array[0]));
    PrintArray(array, sizeof(array)/sizeof(array[0]));
}

int main()
{
    TestSort();
    system("pause");
    return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值