排序算法之选择排序2——堆排序

堆排序是一个不稳定的排序算法,其时间复杂度为O(nlgn),空间复杂度为O(1)。其基本思想是对数组建立一个初始堆,然后进行一系列的交换和调整,最后得到需要的有序序列。
堆排序的一种实现:

template <typename T>
void Adjust(T *array, int parent, int size)    //调整函数
{
    assert(NULL != array && parent >= 0);
    int child = 2*parent + 1;
    while(child < size)
    {
        if(child+1 < size)
            child = Greater<int>()(array[child], array[child+1]) ? child : child+1;
        if(Greater<T>()(array[child], array[parent]))
            swap(array[parent], array[child]);
        else
            break;
        parent = child;
        child = 2*parent + 1;
    }
}

template <typename T>
void HeapSort(T *array, int size)
{
    assert(NULL != array && size > 0);
    if(size == 1)
        return;
    for(int i = ((size-2)>>1); i >= 0; i--)   //建立初始堆
        Adjust(array, i, size);
    while(size > 1)                           //进行交换和调整
    {
        swap(array[0], array[size-1]);
        size--;
        Adjust(array, 0, size);
    }
}

测试函数:

void test5()
{
    int arr[100] = { 0 };
    int sz = sizeof(arr) / sizeof(arr[0]);
    srand((unsigned int)time(0));
    for(int i = 0; i < sz; i++)    //Assign values with random numbers
    {
        arr[i] = rand() % sz;
    }
    for(int i = 0; i < sz; i++)    //print array
        cout << arr[i] << " ";
    cout << endl << endl << endl << "sort:" << endl;
    HeapSort(arr, sz);             //sort
    for(int i = 0; i < sz; i++)    //print array
        cout << arr[i] << " ";
    cout << endl;
    for(int i = 1; i < sz; i++)  //check that the sort is correct
    {
        if(Less<int>()(arr[i], arr[i-1]))
            cout << "sort error! " << i << endl;
    }
}

程序运行结果:
这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值