堆排序

不稳定的排序。

时间复杂度: O(nlgn), 空间复杂度O(1)

适合数据结构:数组,二叉树。

经常用到通过数组进行堆排序:

映射后会发生一些变化:

shot

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define N 1000000
int numbers[N]={0}; // data
void HeapAdjust(int data[], int length, int father){
    if(!data || length < 1 || father >= length || father < 0) return;
    int value = data[father];                                       // set data[0] to save the value of original father
    for(int child = 2*father+1; child < length; child = 2*father+1){
        if(child < length-1 && data[child] < data[child+1]) ++child;
        if(data[child] < value) break;
        else data[father] = data[child];
        father = child;
    }
    data[father] = value;
}
void HeapSort(int data[], int length)
{
    for(int i = length/2-1; i >= 0; --i)
        HeapAdjust(data, length, i);
    for(int i = length-1; i >= 0; --i){
        int tem = data[i];
        data[i] = data[0];
        data[0] = tem;
        HeapAdjust(data, i, 0); // DESC
    }
}
void init_array()
{
    int i;
    /*srand((unsigned) time(NULL));*/
    for(int i = 0; i < N; i++)
        numbers[i] = rand() % N;
}
void print_array()
{
    int i;
    for(i = 0; i < N; i++)
        printf("%d\t", numbers[i]);
}
int main(){
    init_array();
    HeapSort(numbers, N);
    print_array();
    printf("\n");
    return 0;
}

转载于:https://www.cnblogs.com/liyangguang1988/p/3704171.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值