Your Ad Here
首页 | 编程语言 | 网站建设 | 游戏天堂 | 冲浪宝典 | 网络安全 | 操作系统 | 软件时空 | 硬件指南 | 病毒相关 | IT 认证
软讯网络 > 编程语言 > C/C++ > 堆排序heapsortC语言实现
【标  题】:堆排序heapsortC语言实现
【关键字】:heapsortC
【来  源】:http://www.cublog.cn/u/27708/showart.php?id=216999

堆排序heapsortC语言实现

Your Ad Here    这个学期选了《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 1;
}

/*
 * 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算法应用更广泛。
钱塘在线免费影院 西部在线免费电影 铁通西部在线影院:【上一篇】
iterator 辅助函数:【下一篇】
【相关文章】
没有相关文章
【随机文章】
  • GVIM配置文件
  • LINUX下可用免费网络电视
  • Linux高性能集群综述
  • 蚁群算法
  • Unix哲学
  • 开发基于DCOM的局域网聊天室(二)
  • 网上营销模式探讨(一)
  • 一个理解多线程程序中共享变量的好例子
  • VB中用第三方控件打造QQ菜单
  • XP实用技巧:网络备用设置
  • 【相关评论】
    没有相关评论
    【发表评论】
    姓名:
    邮件:
    随机码*
    评论*
          
    |  首 页  |  版权声明  |  联系我们   |  网站地图  |
    CopyRight © 2004-2007 bbb软讯网络 All Rigths Reserved.