首页 > 代码库 > 堆排序

堆排序

不稳定的排序。

时间复杂度: 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 = http://www.mamicode.com/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;
}