当前位置: 首页 >> 程序设计 >> 堆排序C语言实现
 

堆排序C语言实现

作者:      来源:liuguo09.cublog.cn     发表时间:2007-05-04     浏览次数:      字号:    

这个学期选了《Algorithm Design and Analysis》课程,其中有要求实现堆排序Heapsort,并写出相应的设计报告,其中包括算法设计思想、调试通过的源程序、算例以及对结果的分析等。下面仅是heapsort源程序代码实现: 
  

#include <stdio.h>

#define SIZE 10        

#define Left(i)        ((i) << 1)        
#define Right(i)    (((i) << 1) + 1)

void heapsort(int a[], int heapsize);
void maxheapify(int a[], int i, int heapsize);
void swap(int *x, int *y);

int main(int argc, char **argv)
{
    int a[SIZE+1] = { 0, 16, 4, 10, 14, 7, 9, 3, 2, 8, 1 };    
    /* note a[0] is not used */
    int i, heapsize;

    heapsize = SIZE;
    heapsort(a, heapsize);

    for (i = 1; i < SIZE + 1; i++)        /* print the sorted array */
        printf("%d ", a[i]);
    printf("\n");

    return 0;
}

/*
 * heapsort: contains two procedures, one is to build the max-heap,
 * the other is to delete max to gain the sorted array.
 */

void heapsort(int a[], int heapsize)
{
    int i;

    for (i = heapsize / 2; i >= 1; i--)        /* build max-heap */
        maxheapify(a, i, heapsize);        

    for (i = heapsize; i >= 2; i--)            /* delete max */    
    {
        swap(&a[1], &a[i]);
        heapsize--;
        maxheapify(a, 1, heapsize);
    }

}

/*
 * maxheapify: used to let the value at a[i] "float down" in the
 * max-heap so that the subtree rooted at index i becomes a max-heap.
 */

void maxheapify(int a[], int i, int heapsize)
{
    int largest, left, right;

    left = Left(i);
    right = Right(i);

    if (left <= heapsize && a[left] > a[i])
        largest = left;
    else
        largest = i;
    if (right <= heapsize && a[right] > a[largest])
        largest = right;

    if (largest != i)
    {
        swap(&a[i], &a[largest]);
        maxheapify(a, largest, heapsize);    /* recurrsion */
    }

    return;        /* return when largest == i */
}

void swap(int *x, int *y)
{
    int temp;

    temp = *x;
    *x = *y;
    *y = temp;
}


注:虽然heapsort堆排序的时间复杂性和quicksort快速排序一样为O(nlogn),但在实际中还是quicksort算法应用更广泛。

责任编辑 webmaster

 
 
 
 
 
评论更多>>
 
编得真是好 本人刚刚学C语言 有很多不懂的地方 能否向你请教学习语言的方法呢? 看上去和CLRS中的解法很像,呵呵
 
 
发表
 
姓名: QQ:
性别: MSN:
E-mail: 主页:
评分: 1 2 3 4 5
评论内容:
验证码:
  
  • 请遵守《互联网电子公告服务管理规定》及中华人民共和国其他各项有关法律法规。
  • 严禁发表危害国家安全、损害国家利益、破坏民族团结、破坏国家宗教政策、破坏社会稳定、侮辱、诽谤、教唆、淫秽等内容的评论 。
  • 用户需对自己在使用本站服务过程中的行为承担法律责任(直接或间接导致的)。
  • 本站管理员有权保留或删除评论内容。
  • 评论内容只代表网友个人观点,与本网站立场无关。
  •