Heap Data Structure and Heap Sort

参考:http://www.codeproject.com/Tips/732196/Heap-Data-Structure-and-Heap-Sort#xx4775794xx

#include <cstdio>

// The sift function:
// 'sifts down' the a[l] item until heap properties are restored
// ARGS:
//  a[] (INOUT) the array  (where a[l+1], a[l+2] .. a[size-1] is a partial heap)
//  size (IN) number of items of a
//  l (IN) index of the item inserted into the heap
void sift(int a[], int size, int l)
{
    int i, j, x;
    i = l;
    j = 2 * i + 1;
    x = a[i];
    while (j < size)
    {
        // the maximum of left and right child
        if (j < size - 1)
        if (a[j] < a[j + 1])
            ++j;
        if (x >= a[j])
            break;
        a[i] = a[j];
        i = j;
        j = 2 * i + 1; // sift
    }
    a[i] = x;
}

// makes the heap using the R.W.Floyd's algorithm
// ARGS:
//  a[] (INOUT) the array wherein the heap is created
//  size (IN) the size of the array
void make_heap(int a[], int size)
{
    int l = size / 2;
    while (l)
    {
        --l;
        sift(a, size, l);
    }
}

void heapsort(int a[], int size)
{
    int l = 0, r = size;
    make_heap(a, size);

    while (r > 1)
    {
        int tmp = a[0];
        --r;
        a[0] = a[r];
        a[r] = tmp;
        sift(a, r, 0);
    }
}

int main()
{
    int a[10] = { 1, 3, 2, 5, 11, 45, 7, 9, 21, 0 };
    heapsort(a, 10);
    for (int i = 0; i < 10; i++)
    {
        printf("%d ", a[i]);
    }

    return 0;
}

 

posted @ 2016-04-27 20:14  ht-beyond  阅读(259)  评论(0编辑  收藏  举报