c语言 实现堆排序算法

       今天在《算法导论》第二版看完了“堆排序”算法,就顺便用C语言实现了一下。

       堆排序算法的核心思想,使用一种二叉堆的数据结构来存储数据,其中二叉堆(最小二叉堆)的主要性质为:

       1 父节点小于所有的子节点的数值(注:最小堆)

       2 二叉堆为满二叉树

      其中堆排序算法,主要包括一下几个主要的部分:

       1 保持堆特性  MaxHeapify 函数实现

       2 建立堆  BuildHeap函数实现

       3 堆排序实现  HeapSort函数实现

      具体的C语言实现代码如下:

   功能函数:

#include "heap.h"
#include<stdio.h>

int Parent(int i)
{
	return i/2;
}

int Left(int i)
{
	return 2*i + 1;
}

int Right(int i)
{
	return 2*i + 2;
}

void Exchange(int *a ,int *b)
{
	int temp = *a;
	*a = *b;
    *b = temp;
}

void MaxHeapify(Heap heap, int i)
{
	int l = Left(i);
	int r = Right(i);
	int largest;

	if((l <= heap->size-1) && ((heap->key)[l] > (heap->key)[i]))
		largest = l;
	else 
		largest = i;

	if((r <= heap->size-1) && ((heap->key)[r] > (heap->key)[largest]))
		largest = r;

	if( largest != i )
	{
		Exchange(&(heap->key)[i], &(heap->key)[largest]);
		MaxHeapify(heap, largest);
	}
}

void BuildHeap(Heap heap)
{
	int length = heap->size;
	int i =( length-1)/2 + 1;
	while(i-- > 0)		
		MaxHeapify(heap, i);
}

void HeapSort(Heap heap)
{
	int length = heap->size;
	int i;

	BuildHeap(heap);
	
	for(i = length - 1; i> 0; i--)
	{
		Exchange(&(heap->key)[i], &(heap->key)[0]);
		heap->size--;
		MaxHeapify(heap, 0);	
	}
}

主函数 main.c

#include<stdio.h>
#include "heap.h"
#include<time.h>
#include<stdlib.h>

int main()
{
    time_t t;
    srand((unsigned) time(&t));
	int i = 0;
	int test[10];
	for(i = 0;i < 10; i ++)
		test[i] = rand()%100;

	Heap heap = malloc(sizeof(struct heapStruct));
	heap->capacity = MAX;
	heap->size = 10;
	heap->key = malloc(sizeof(int)*heap->size);
	heap->key = test;

	for(i = 0;i < 10; i ++)
		printf("%d ",heap->key[i]);
	printf("\n");
	HeapSort(heap);

	for(i = 0;i < 10; i ++)
		printf("%d ",test[i]);
	
	printf("\n");

	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值